2

我在使用 GSON 和 Jackson 在 android 中解析大约 11MB 的大型 JSON 时遇到问题。问题是发生内存不足错误异常并且堆大小不足以完成此过程。这是我的纸模型课

public class Paper {

public int primaryKey;

public String title;

public int entry;

public Boolean favourite;

public String comment;

public int opt;

public int score;
}

这是我的响应模型类

public class Response {

public List<Paper> papers;

} 

这是我的 JSON 字符串

{"Paper":[[{"abstract":"Not Available","title":"A Fully Intraocular 0.0169mm<sup>2<\/sup>/pixel 512-Channel Self-Calibrating Epiretinal Prosthesis in 65nm CMOS","primaryKey":3,"entry":9,"score":-1,"comment":null,"favourite":false,"opt":1},{"abstract":"Not Available","title":"A Scalable 2.9mW 1Mb/s eTextiles Body Area Network Transceiver with Remotely Powered Sensors and Bi-Directional Data Communication","primaryKey":14,"entry":9,"score":-1,"comment":null,"favourite":false,"opt":1},{"abstract":"Not Available","title":"A 0.18µm CMOS SoC for a 100m-Range 10fps 200×96-Pixel Time-of-Flight Depth Sensor","primaryKey":20,"entry":9,"score":-1,"comment":null,"favourite":false,"opt":1},{"abstract":"Not Available","title":"A 12b 1.6GS/s 40mW DAC in 40nm CMOS with >70dB SFDR over Entire Nyquist Bandwidth","primaryKey":26,"entry":9,"score":-1,"comment":null,"favourite":false,"opt":1},{"abstract":"Not Available","title":"All-Digital Hybrid Temperature Sensor Network for Dense Thermal Monitoring","primaryKey":49,"entry":9,"score":-1,"comment":null,"favourite":false,"opt":1},{"abstract":"Not Available","title":"32Gb/s Data-Interpolator Receiver with 2-Tap DFE in 28nm CMOS","primaryKey":51,"entry":9,"score":-1,"comment":null,"favourite":false,"opt":1},{"abstract":"Not Available","title":"A 93% Efficiency Reconfigurable Switched-Capacitor DC-DC Converter Using On-Chip Ferroelectric Capacitors","primaryKey":60,"entry":9,"score":-1,"comment":null,"favourite":false,"opt":1},{"abstract":"Not Available","title":"A 45nm CMOS Near-Field Communication Radio with 0.15A/m RX Sensitivity and 4mA Current Consumption in Card Emulation Mode","primaryKey":61,"entry":9,"score":-1,"comment":null,"favourite":false,"opt":1}]]}

我不知道我在哪里做错了。我因为论文而变得无效。

4

2 回答 2

4

在读取完整输入之前,使用流式解析器并尝试在读取内容时对其进行处理。这样您就可以避免将完整的结构保存在内存中。

例如,如果您的输入 JSON 是一个巨大的数组,您可以逐个元素地处理输入。

于 2013-01-19T08:56:22.977 回答
0

您也可以尝试使用Genson,检查数据绑定 api ( new Genson().deserialize(json, ToClass.class)) 或直接使用流 api。

这取决于你想做什么。如果您需要内存中的所有数据,那么没有太多选择,您需要增加它。如果您可以在阅读时处理内容并且不需要始终在内存中使用它,那么它将与流 api 一起工作(非常高效并且使用极少的内存)。

编辑 解决方案

  1. 您想使用数据绑定,因此您要做的工作更少。首先看看这个项目https://github.com/joelittlejohn/jsonschema2pojo它允许您基于 json 示例生成 java bean 类。当您生成的类只是new Genson().deserialize(json, MyGeneratedClass.class);在执行多个 ser/deser 时,您应该重用 Genson 实例以获得更好的性能。

  2. 如果您不想使用 1),如果结构在运行时发生更改(这将阻止生成类),或者您仍然有内存问题,请使用Gensons 流 api。它高效、高效且易于使用。

于 2013-01-19T11:27:31.620 回答