Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse json, using org-json libraries?

Tags:

java

json

parsing

Looking for org-json solutions only please **

Suppose you deal with a structure, as follows.

Using json-org, how can i get an array of Tests, if this entire json is represented in a String s?

Using Google's gson, it's easy to do by testing what type given object is ... i am missing something simple here with json-org libraries

{
   "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
   }
}
like image 860
James Raitsev Avatar asked Feb 25 '23 00:02

James Raitsev


1 Answers

It so happens i got it before someone else had a chance to help. In case someone else has similar question, i am posting an answer below:

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));
}
like image 156
James Raitsev Avatar answered Mar 06 '23 03:03

James Raitsev