1
我使用下面的代碼從我的服務器處理REST響應:解析字符串JSONTokener到的JSONObject OR JSONArray
if (response.getEntity() != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
try {
rr.jsonObject = new JSONObject(tokener);
} catch (JSONException e) {
e.printStackTrace();
Log.d("parsing", "creating json array");
try {
rr.jsonArray = new JSONArray(tokener);
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}
如果響應是一個JSONObject的,它完美的作品,但如果服務器返回一個JSONArray ,第二個try塊也會拋出,儘管它是正確的json。
03-30 14:09:15.069: W/System.err(6713): org.json.JSONException: End of input at character 314 of [{"__className":"stdClass","char3code":"DEU","fips_name":"Germany","alternate_names":"Germany, Deutschland, Allemagne, Alemania"},{"__className":"stdClass","char3code":"USA","fips_name":"United States","alternate_names":"United States of America, Vereinigte Staaten von Amerika, \u00c9tats-Unis, Estados Unidos"}]
是的,就是這樣。謝謝! –