在我的代码中,当我将JSONObjects放在JSONArray中时,可以使用getJSONObject调用读取它。但是,当我在另一个JSONObject中添加JSONArray然后读取数组并尝试调用getJSONObject时,出现错误JSONArray[0] is not a JSONObject.
如何避免此错误?
final JSONArray jsonArray = new JSONArray();
jsonArray.put(new JSONObject().put("id", "id1"));
jsonArray.put(new JSONObject().put("id", "id2"));
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println("--------------- everything is smooth and fine --------------------: " + jsonArray.getJSONObject(i));
}
// stuffed array inside an object.
final JSONObject jsonObject = new JSONObject();
jsonObject.append("key", jsonArray);
// refetched the array.
final JSONArray responseArray = jsonObject.getJSONArray("key");
for (int i = 0; i < responseArray.length(); i++) {
// error - JSONArray[0] is not a JSONObject.
System.out.println("----------------- errors out ------------------: " + responseArray.getJSONObject(i));
}
使用put
来代替:
// stuffed array inside an object.
final JSONObject jsonObject = new JSONObject();
jsonObject.put("key", jsonArray);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句