我正在使用此代碼來解析從我的服務器獲得的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.增加這個數量雖然不會改變任何東西。 任何有關問題背後的原因,將不勝感激。此外,如果您看到有待改進的餘地,請隨時對我的代碼發表評論。 :)