如何使用org-json库解析json?

4

请只提供org-json解决方案 **

假设你处理的结构如下所示。

使用 json-org,如果这整个 JSON 表示为一个 String s,我该如何获得一个 Tests 数组?

使用 Google 的 gson,通过测试给定对象的类型很容易实现... 我在 json-org 库中错过了一些简单的东西。

{
   "Groups":{
      "Test":[
         {
            "Test Number":123456,
            "Channel":"TEST",
            "environment":"A",
            "output event":[
               {
                  "description":"very good description",
                  "value":123,
                  "active":true
               },
               {
                  "description":"another very good description",
                  "value":456,
                  "active":true
               }
            ],
            "active":true,
            "instrument":"ABC"
         },
         {
            "Test Number":547985,
            "Channel":"some new channel",
            "environment":"B",
            "output event":[
               {
                  "description":"reject",
                  "value":123,
                  "active":true
               },
               {
                  "description":"ack",
                  "value":456,
                  "active":true
               }
            ],
            "active":true,
            "instrument":"XYZ"
         }
      ],
      "name":"A clever name",
      "active":true
   }
}
1个回答

8

恰好在别人还没有机会提供帮助之前,我就解决了问题。如果有其他人有类似的问题,我在下面发布了一个答案:

JSONObject o = new JSONObject(s);

JSONArray arrayOfTests = (JSONArray) ((JSONObject) o.get("Groups")).get("Test");

for (int i = 0; i < arrayOfTests.length(); i++) {
    System.out.println(arrayOfTests.get(i));
}

2
JSONObject o = new JSONObject(s); 在这行中我收到了一个错误,“构造函数JSONObject未定义”。 - Hardik Patel
1
在你的情况下,“s”是什么?我相信应该是String对象。 - James Raitsev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接