我在解析此特定JSONObject时遇到问题,

这是对象:

{"status":1,"dds":{"id":1,"name":"DDS1","description":"This is DDS 1","children":[{"id":2,"order":1,"type":1,"children":[{"id":3,"order":1,"type":3,"children":[]},{"id":4,"order":2,"type":2,"children":[]}]}]}}


该对象存储在名为result的变量中,这是解析它的代码:

JSONObject jsonObj = null;
JSONArray jsonArr = null;
try {
    jsonObj = new JSONObject(result);
    jsonArr = jsonObj.getJSONArray("dds");

} catch (JSONException e) {
e.printStackTrace();
}


它给了我这个错误:

org.json.JSONException: Value {"id":1,"children":[{"type":1,"order":1,"id":2,"children":[{"type":3,"order":1,"id":3,"children":[]},{"type":2,"order":2,"id":4,"children":[]}]}],"description":"This is DDS 1","name":"DDS1"} at dds of type org.json.JSONObject cannot be converted to JSONArray


我试图将其分解为子阵列。我要去哪里错了?

@爱先生

这是我对您的代码的输出

最佳答案

您正在调用jsonArr = jsonObj.getJSONArray("dds");,但是dds不是数组,它是JSON对象,如果格式化JSON,则可以清楚地看到它:

{
   "status":1,
   "dds":{
      "id":1,
      "name":"DDS1",
      "description":"This is DDS 1",
      "children":[
         {
            "id":2,
            "order":1,
            "type":1,
            "children":[
               {
                  "id":3,
                  "order":1,
                  "type":3,
                  "children":[

                  ]
               },
               {
                  "id":4,
                  "order":2,
                  "type":2,
                  "children":[

                  ]
               }
            ]
         }
      ]
   }
}


因此,您只需要呼叫JSONObject dds = jsonObj.getJSONObject("dds"),如果您想要孩子,就可以呼叫JSONArray children = jsonObj.getJSONObject("dds").getJSONArray("children");

private static final String json = "{\"status\":1,\"dds\":{\"id\":1,\"name\":\"DDS1\",\"description\":\"This is DDS 1\",\"children\":[{\"id\":2,\"order\":1,\"type\":1,\"children\":[{\"id\":3,\"order\":1,\"type\":3,\"children\":[]},{\"id\":4,\"order\":2,\"type\":2,\"children\":[]}]}]}}";

public static void main(String[] args) throws JSONException
{
    JSONObject jsonObj = new JSONObject(json);
    JSONObject dds = jsonObj.getJSONObject("dds");

    JSONArray children = dds.getJSONArray("children");
    System.out.println("Children:");
    System.out.println(children.toString(4));

    JSONArray grandChildren = children.getJSONObject(0).getJSONArray("children");
    System.out.println("Grandchildren:");
    System.out.println(grandChildren.toString(4));
}


产生:

Children:
[{
    "children": [
        {
            "children": [],
            "id": 3,
            "order": 1,
            "type": 3
        },
        {
            "children": [],
            "id": 4,
            "order": 2,
            "type": 2
        }
    ],
    "id": 2,
    "order": 1,
    "type": 1
}]
Grandchildren:
[
    {
        "children": [],
        "id": 3,
        "order": 1,
        "type": 3
    },
    {
        "children": [],
        "id": 4,
        "order": 2,
        "type": 2
    }
]

10-07 19:15