zholmes1 zholmes1 - 1 year ago 88
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.