我正在使用此代码来解析从我的服务器获得的JSON数组。Android ByteArrayOutputStream损坏HTTP GET JSONArray
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;
此代码在我的手机上效果很好。不幸的是,当我在谷歌Nexus 7的虚拟设备上使用Genymotion仿真器时,JSON数组稍有改动。 JSON数组的95%是好的,但它被截断接近尽头,在字符1253是随机丢失约4 JSON数组的字符,所以我越来越:
org.json.JSONException: Expected ':' after top_id at character 1253 of [{"top_id":6,"top_url":
我想这是模拟器存在一些内存问题。它的基本内存是1024.增加这个数量虽然不会改变任何东西。 任何有关问题背后的原因,将不胜感激。此外,如果您看到有待改进的余地,请随时对我的代码发表评论。 :)