Encountering a memory issue when trying to parse a hefty JSON file using the Jackson library in an Android

Currently, I am facing a challenge with parsing a substantial JSON response from the server using the Jackson library. The size of the JSON file is approximately 7-8 MB.

The error that I encountered while running the code snippet below:

ObjectMapper mapper = new ObjectMapper();
JsonNode rootParser = mapper.readValue(is, JsonNode.class);

has resulted in the following exception:

    01-14 13:13:20.103: E/AndroidRuntime(25468): FATAL EXCEPTION: Thread-13
    01-14 13:13:20.103: E/AndroidRuntime(25468): java.lang.OutOfMemoryError
    01-14 13:13:20.103: E/AndroidRuntime(25468): at java.util.ArrayList.add(ArrayList.java:123)
01-14 13:13:20.103: E/AndroidRuntime(25468):    at org.codehaus.jackson.node.ArrayNode._add(ArrayNode.java:722)
...
(complete exception stack trace)
...
    

Despite attempting various solutions, I have not been able to successfully parse such a large dataset on an Android device.

Answer №1

Dealing with JSON data can be memory intensive, especially when using tree models that can consume a significant amount of memory. While most libraries build trees using Lists and Maps, which are heavy-weight structures, an alternative approach is to utilize Plain Old Java Objects (POJOs) for better memory efficiency. By creating POJOs that mirror your JSON structure, you can reduce memory usage significantly.

MyValue value = mapper.readValue(json, MyValue.class);

This method works well with Jackson, Gson, Genson, and other Java JSON libraries, offering not only lower memory footprint but also improved performance compared to working with JSON trees directly. Additionally, breaking down multi-megabyte content into smaller sequences can further optimize memory usage, whether processing individual items as JsonNodes or POJOs.

Answer №2

Utilizing the gson library, the following code allows for seamless retrieval of files larger than 50Mb:

public static <T extends Object> T readFile(String file_path, Type type) {

    GsonBuilder gson_builder = new GsonBuilder();

    final SimpleDateFormat sdf_date     = new SimpleDateFormat("yyyy-MM-dd");
    final SimpleDateFormat sdf_datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    gson_builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>(){

        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

            try {
                if (json.getAsJsonPrimitive().getAsString().length() == 10)
                    return sdf_date.parse(json.getAsJsonPrimitive().getAsString());
                else
                    return sdf_datetime.parse(json.getAsJsonPrimitive().getAsString());

            } catch (ParseException e) {
                Log.e("JSON", "Error deserializing dates in JSON: " + json.getAsJsonPrimitive().getAsString());
                return null;
            }
        }

    });

    Gson gson = gson_builder.create();

    File jsonFile = new File(file_path);

    FileReader reader = null;

    try {
        reader = new FileReader(jsonFile);

        return gson.fromJson(reader, type);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            reader.close();

            if (jsonFile.exists())
                jsonFile.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return null;
}

Experiment with this library, it's reliable. We mainly use Jackson on the server side as it tends to be slower on Android compared to gson based on our tests.

Answer №3

Consider utilizing the following code snippet:

JsonNode rootNode = mapper.readTree(inputSource);

as an alternative method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can Maven be utilized solely for executing the Selenium plugin?

In our current pom.xml file, we have both the build settings and the selenium execution using the selenium-maven-plugin. I am interested in separating these into two separate pom files - one for building and running unit tests, and another dedicated speci ...

Updating the dependencies in package.json is not reflecting the changes

Attempting to run my friend's project on my machine with the angular-cli led me to discover that the dependencies in the package.json were outdated. In an effort to update them, I used the following commands: npm i -g npm-check-updates npm-check-upda ...

Retrieving a specific item using its ID from a JSON file with Ionic 5

Newcomer's query For multiple Ionic pages, I require fetching a specific item by ID from a centralized JSON file. The structure of my JSON data is as follows: { "items": [ { "id":"0", "link&q ...

How can Cucumber be used to validate data from multiple JSON files?

I am currently working with a collection of JSON files within my automation framework. Each JSON file consists of an array containing multiple similar JSON objects. My goal is to utilize these files for validation in a web application using Cucumber and Se ...

What is the proper way to send a HTTP status code 409 (conflict) and a JSON response from a spring REST API when a duplicate email is detected while a user is registering

I have attempted a few solutions so far, including: Using the Response object, but I prefer to avoid utilizing the servlet API of JSP. Trying a solution that returns an HTML response with a status code, however, I need it to be JSON instead. Here is a ...

Transforming JArray into an Object with specific attributes

I am faced with the challenge of converting a JArray into an Object using Attributes because I cannot modify the existing call in a decoupled class: var message = JsonConvert.DeserializeObject(e.Message, messageType) The JSON data to be converted is as f ...

Is it conceivable to exploit JSON responses with appropriate JavaScript string escaping to launch an XSS attack?

Exploiting JSON responses can occur when Array constructors are overridden or when hostile values are not properly JavaScript string-escaped. To combat this, Google has implemented a technique where all JSON responses are prefixed with a specific code sni ...

Angular select tag failing to display input data accurately

When constructing select type questions for my web app using a JSON file, the code snippet for the select tag appears as follows: <div class="form-group" ng-class="{ 'has-error': form.$submitted && form[field.id].$invalid }" ng-if="fi ...

Transform file paths into JSON format with the help of bash and jq

Is it possible to utilize jq for bash in order to convert the example below? The goal is to transform the file paths into json according to the provided example const data = [ "/parent/child1/grandchild1" "/parent/child1/grandchild2" "/parent ...

"Converting PostgreSQL data into a PHP array with the column serving as the index

Is it possible to return a JSON object directly from a PostgreSQL query? Let's say the query produces results like this: who count ================= mary 2 had 9 a 12 lamb 9 The database has columns "who" and "count." I ...

Python Tutorial: Decoding JSON Objects with Unicode Encoding

I recently stored a JSON object in a file using the repr function like so: f = open('file', 'w') f.write(repr(my_json)) f.close() After saving, I noticed that the JSON data now has leading 'u' characters denoting unicode enc ...

Encountering a JavaScript runtime error while trying to access and interpret JSON

Currently, I'm facing a challenge with converting a C# list of string types into a JSON object. The issue arises when trying to read this JSON object later in JavaScript. On the other hand, the process seems to work fine when dealing with a C# list of ...

Is there a way to execute an SQL query using ajax?

I recently came across an interesting problem involving passing an SQL query through to an ajax file. let qry = mysqli_query($this->con,"SELECT * FROM products"); To ensure proper containment, I embedded the variable within HTML using the following co ...

Issue with Google Calendar: Unable to locate com.google.api.client.json.JsonFactory.fromInputStream

Currently, I'm developing a Spring-MVC application and I'm facing an issue while trying to integrate Calendar functionality. The problem seems to be related to authentication due to a json error. I have been using Googles sample code but it appea ...

Struggling to access a remote URL through jQuery's getJSON function with jsonp, but encountering difficulties

Currently, I am attempting to utilize the NPPES API. All I need to do is send it a link like this and retrieve the results using jQuery. After my research, it seems that because it is cross-domain, I should use jsonp. However, I am facing difficulties m ...

Is it possible for me to utilize pure JavaScript for loading JSON data?

I am interested in dynamically creating a Google Map by loading data through AJAX. To achieve this, I am using a JSON object that mimics the structure of the GM API to construct the map and jQuery for AJAX loading. For example: "object": { "div": "ma ...

Definition of JSON Schema attribute: Field schema not supported for field... : Type of field is undefined

I am in the process of creating a form that is based on a JSON schema and utilizing the react-jsonschema-form component for ReactJS. The purpose of this form is to allow users to input various settings (such as CSS/HTML selectors) that will be used to ext ...

Can an Angular 5 web application be developed without using Node.js/npm?

I want to develop an Angular 5 web application using Java, but my boss prefers not to use Node.js/npm. Is it possible to build an app without Node.js/npm and rely solely on Java? Most of the resources I've come across recommend using Node.js/npm, inc ...

Discovering WebElements: The key to effective web development

Our automation process currently relies heavily on @FindBy with Selenium/WebDriver/Java. This includes: @FindBy(css="a[name='bcrumb']") protected List<WebElement> breadCrumbLinks; @FindBy(id="skuError") protected WebElement skuE ...

Waiting for Angular pages in Selenium with Protractor JavaScript code

I'm currently in the process of testing an AngularJS page and utilizing Selenium (Java) to create automation scripts for it. Below is the code snippet that I've implemented to ensure synchronization with the page before moving on to the next scr ...