开发者

Why is Android's JSONObject retained in memory?

I am working on an OutOfMemory exception generated when a really large JSONObject is created but never garbage collected by Android's framework. On each subsequent update the memory leak just gets bigger and bigger till I run out of memory. We have a large data structure that changes over time and on each update we send the whole datastructure to the client and refresh it. I know that is not the best way to do it, but changing the whole infrastructure just for Mobile is going to take some time and convincing to do.

As for the here and now, when an Object goes out of scope in Java, it should be marked as available to be garbage collected. I am using the Eclipse MAT tool to do my memory analysis and according to the tool, each开发者_Go百科 String I parse out of the JSONObject has a link back to the original JSONObject. A fix I have is I created a remove function where I iterate through each of the JSONObjects keys and call JSONObject.remove(key) after I am done parsing, that works like a charm and all memory is collected. However, why do I need to do that? I should not have to do that to an out of scope object. Any ideas?

Thanks in advance!

Jared Sheehan


Maybe it's best to convert your JSON response into a POJO as soon as you receive it. The Jackson JSON parser will do that for you in two lines of code and can also turn it back into your JSON Object if you ever need to do that.

Jackson is very fast (they claim the fastest of all the parsers) so you won't take much of a performance hit.

Check out this tutorial on their website.

from the tutorial, you can take this simple JSON object:

{
    "name":
    {
        "first":"Joe",
        "last":"Sixpack"
    },
    "gender":"MALE",
    "verified":false,
    "userImage":"Rm9vYmFyIQ=="
}

and parse it into your own object with this code:

ObjectMapper mapper = new ObjectMapper(); // can reuse, share globally
User user = mapper.readValue(new File("user.json"), User.class);

Just so you know, I also had issues with memory retention in my latest Android project and eventually gave up on using JSON altogether.

Good luck!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜