我正在使用此代码解析从服务器获取的 JSON 数组。
try {
URL u = new URL("http://54.68.139.250/get_user_likes");
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setRequestMethod("GET");
conn.connect();
InputStream is = conn.getInputStream();
byte[] b = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ( is.read(b) != -1)
baos.write(b);
String JSONResp = new String(baos.toByteArray());
JSONArray arr = new JSONArray(JSONResp);
for (int i=0; i < arr.length(); i++) {
result.add(convertArticle(arr.getJSONObject(i)));
}
return result;
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
此代码在我的手机上运行良好。不幸的是,当我在 Google Nexus 7 的虚拟设备上使用 Genymotion 模拟器时,JSON 数组略有改变。95% 的 JSON 数组很好,但它在接近尾声时被截断,并且在字符 1253 处随机丢失了 json 数组的大约 4 个字符,所以我得到:
org.json.JSONException: Expected ':' after top_id at character 1253 of [{"top_id":6,"top_url":
我认为这是模拟器的一些内存问题。它的基本内存是 1024。虽然增加这个数量并不会改变任何东西。任何有关问题背后原因的提示将不胜感激。另外,如果您发现有改进的余地,请随时评论我的代码。:)