使用Gson解析大型JSON响应时发生OutOfMemoryError [英] OutOfMemoryError when using Gson to parse a large JSON response

查看:447
本文介绍了使用Gson解析大型JSON响应时发生OutOfMemoryError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这会导致旧版Android设备上的部分用户出现OutOfMemoryException。如何在不耗尽内存的情况下解析这个大型响应?

解决方案

解析大型数据一次往往是棘手和麻烦的。然而, Gson 附带了一些不错的功能。



您应该寻找 com.google.gson。 stream.JsonReader 使用流执行json解析。这将允许您在下载数据时按增量顺序解析数据,并将设备从OutOfMemory错误中备用。

有关更多信息,请阅读


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?

解决方案

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.

这篇关于使用Gson解析大型JSON响应时发生OutOfMemoryError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆