繁体   English   中英

如何防止 JSONArray[0] is not a JSONObject 错误?

[英]How to prevent JSONArray[0] is not a JSONObject error?

在我的代码中,当我将 JSONObjects 放入 JSONArray 中时,我可以使用 getJSONObject 调用读取它但是当我将 JSONArray 添加到另一个 JSONObject 中然后获取数组然后尝试调用 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM