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

时间:2011-05-31 19:28:58

标签: java json parsing

只需寻找org-json解决方案**

假设您处理结构,如下所示。

使用json-org,如果整个json在String s中表示,我如何获得测试数组?

使用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 个答案:

答案 0 :(得分: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));
}