如何在java中读取嵌套的json列表?

i5desfxk  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(309)

我需要得到类型值和网络使用下载值和列表是动态的
json响应为

{
  "count": 2,
  "devices": [
    {
      "name": "xyz",
      "type": 1,
      "subType": 0,
      "signalStrength": -37,
      "dataUsage": {
        "download": 84,
        "upload": 84
      },
      "networkUsage": {
        "download": 0,
        "upload": 0
      },
      "speed": {
        "download": 0,
        "upload": 0
      }
    },
    {
      "name": "abcd",
      "type": 2,
      "subType": 0,
      "signalStrength": -37,
      "dataUsage": {
        "download": 84,
        "upload": 84
      },
      "networkUsage": {
        "download": 0,
        "upload": 0
      },
      "speed": {
        "download": 0,
        "upload": 0
      }
    }
  ]
}

我试过这种方法,结果出错了。

JSONArray jsonarray = new JSONArray(response);
System.out.println(String.format("JSONArray length => %d", jsonarray.length()));

for (int i = 0; i < jsonarray.length(); i++) {
        JSONObject obj1 = jsonarray.getJSONObject(i);
        String name = obj1.getString("name");
        int type = obj1.getInt("type");
        System.out.println(name);
        System.out.println(type);
}

线程“main”org.json.jsonexception中的异常:jsonarray文本必须在org.json.jsontokener.syntaxerror(jsontokener)的字符1处以“[”开头。java:496)在org.json.jsonarray。java:115)在org.json.jsonarray。java:159)在com.calix.pages.test.main(test。java:91)

dtcbnfnu

dtcbnfnu1#

JSONObject jsonobj = new JSONObject(response);
JSONArray jsonarray = jsonobj.getJSONArray("devices");
for (int i = 0; i < jsonobj.getInt("count"); i++) {
        JSONObject obj1 = jsonarray.getJSONObject(i);
        String name = obj1.getString("name");
        int type = obj1.getInt("type");
        System.out.println(name);
        System.out.println(type);
}

相关问题