Search code examples
javaandroidjsonjacksonloopj

Android: Stream a large JSON Array produced from loopj's AsyncHttpClient


This is my first question, I hope I didn't make any mistake..

I got a nasty long json array from from the returning value of 'onSuccess()' in this format:

[
    {
     "label1":"value1",
     "label2":"value2",
     "label3":"value3",
     ....
    },
    {
     "label1":"value1",
     "label2":"value2",
     "label3":"value3",
     ....
    },
    ....
]

when I try to convert this to String and parse it using jackson's usual 'mapper', I got the dreaded Out of memory exception. Which makes me think that I need to stream this large json instead.

I went to the example of jackson provided here, but the example doesn't seems to help me much

I wonder if I incapable of searching or I'm just a plain stupid in programming, but it would be much pleasure if someone could direct me to good example.

my current effort:

client.get(
     get_all_item_url,
     new JsonHttpResponseHandler() {
       @Override
       public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable e) {
                        ....
                        }


      @Override
      public void onSuccess(JSONArray response) {
           ObjectMapper mapper = new ObjectMapper();
           ProductModel[] productModels = null;
           try {
               productModels = mapper.readValue(response.toString(),TypeFactory.defaultInstance().constructArrayType(ProductModel.class));
               } catch (IOException e) {
                    e.printStackTrace();
               }
           ....
      }
});

Solution

  • You should avoid response.toString() call. You can get one element from array and parse it. It is not real streaming, but it noticeable reduce memory consumption.