Out of memory exception in gson.fromJson()

后端 未结 4 782
醉话见心
醉话见心 2021-01-04 21:21

I use the following code for converting Json string(strWebserviceResult) to my Object:

EntMyClass entMyClass = gson.fromJson(strWebserviceResult,EntMyClass.c         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-04 21:49

    First of all. Do you really need to load 2.5MB data into memory?
    At first there is created a big string, then it's parsed (another objects in memory), and then there is created a huge instance of EntMyClass. This approach is really inefficient.

    I guess you have List in this object. Having only information you've provided I'd suggest to stream data into database. Then you can create adapter to show data in ListView.

    There is a lot of ways how to do it. I'm using Jackson library because is the fastest, GSON should have similar functions.

    Assuming you have a list in this object below is example how to store json array in database:

        //create parser
        final JsonParser jsonParser = objectMapper.getJsonFactory().createJsonParser(inputStream);
    
        JsonToken jsonToken = jsonParser.nextToken();
        while ((jsonToken = jsonParser.nextToken()) != null && jsonToken != JsonToken.END_ARRAY) {
            //map json object to ItemClass
            final ItemClass item = jsonParser.readValueAs(ItemClass.class);
            //store in database
            itemDAO.insert(item);
        }
    

    And surround it with database transaction, not only data will be rollback in case of error but it's also more efficient.

提交回复
热议问题