我以前尝试过使用树结构。JSON 响应大约为 3.5MB,因此尝试以这种方式解析它会导致旧设备内存不足是可以理解的。
我的问题是:为什么在我切换到流式 JsonReader 之后,我仍然会收到 OutOfMemoryException?我什至将响应保存到 sd 卡上的 .json 文件并从那里读取,这样字符串就不需要存储在内存中。
List<CurrencyPair> currencyPairs = new ArrayList<CurrencyPair>();
URL url = new URL("http://pubapi.cryptsy.com/api.php?method=orderdatav2");
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath() + "/zTrader");
directory.mkdirs();
File file = new File(directory, "cryptsy_response.json");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
BufferedWriter out = new BufferedWriter(new FileWriter(file));
char[] cbuf = new char[255];
while ((in.read(cbuf)) != -1) {
out.write(cbuf);
}
in.close();
out.close();
FileInputStream fis = new FileInputStream(file);
InputStreamReader fileInputStreamReader = new InputStreamReader(fis);
Reader bufferedReader = new BufferedReader(fileInputStreamReader);
JsonReader reader = new JsonReader(bufferedReader);
reader.beginObject();
Map<CurrencyPair, Integer> currencyPairs_MarketIds = new HashMap<CurrencyPair, Integer>();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("success")) {
reader.nextInt();
}
else if (name.equals("return")) {
reader.beginObject();
while (reader.hasNext()) {
String pairString = reader.nextName();
String[] currencies = pairString.split("/");
CurrencyPair currencyPair = new CurrencyPair(currencies[0], currencies[1]);
currencyPairs.add(currencyPair);
reader.beginObject();
while (reader.hasNext()) {
if (reader.nextName().equals("marketid")) {
Integer id = Integer.valueOf(reader.nextString());
currencyPairs_MarketIds.put(currencyPair, id);
}
else {
reader.skipValue();
}
if (sleep)
Thread.sleep(25);
}
reader.endObject();
if (sleep)
Thread.sleep(25);
}
}
}
reader.close();
file.delete();