zholmes1 zholmes1 - 2 years ago 174
JSON Question

OutOfMemoryError when using Gson to parse a large JSON response

URL url = new URL("http://pubapi.cryptsy.com/api.php?method=orderdatav2");
CryptsyCurrencyPairsReturn response = gson.fromJson(new InputStreamReader(url.openStream()), CryptsyCurrencyPairsReturn.class);

This results in an OutOfMemoryException for some of my users on older Android devices. How can I parse this large response without running out of memory?

Answer Source

Parsing large data in one-go is always tricky and troublesome. However Gson comes with some nice features to support that too.

You should look for com.google.gson.stream.JsonReader to perform json parsing using streams. This will allow you to parse the data in an incremental order while its being downloaded and will spare devices from OutOfMemory errors.

For more info, read this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download