【FAQ】解决org.json.JSONException: JSONArray[0] is not a JSONArray.

【报错】

org.json.JSONException: JSONArray[0] is not a JSONArray.

at org.json.JSONArray.getJSONArray(JSONArray.java:278)

【解决】

修改代码:

将 .getJSONArray(0) 修改为  .getJSONObject(0)

return allTimeSlot.getJSONArray(0);

-->

return new JSONArray().put(allTimeSlot.getJSONObject(0));

【根因分析】

JSONArray的内容是在"[]"中的

JSONObject的内容是在"{}"中的

虽然allTimeSlot是一个JSONArray,但是它的第一个元素是一个JSONObject

所以要用getJSONObject(0)这个方法去获取,而不能用getJSONArray去获取

如下,整体是一个JSONArray,但是其中的每一个元素都是JSONObject:

[
    {
        "a":"aaa"
    },
    {
        "b":"bb"
    }
]

如果仍期待生成一个JSONArray,那么应该新建一个JSONArray,然后用put方法把JSONObject插入

猜你喜欢

转载自blog.csdn.net/weixin_42534940/article/details/82782415