Access to the values in a multi-level JSON-structure

Mark Korzhov picture Mark Korzhov · Nov 19, 2013 · Viewed 18.9k times · Source

There is my JSON-structure:

{
   "date":"19.11.2013",
   "parent":{
      "child1":[
         {
            "date":"2013-11-19",
            "time":"10:30",
         },
         {
            "date":"2013-11-19",
            "time":"12:20",
         }
      ],
      "child2":[
         {
            "date":"2013-11-19",
            "time":"10:30",
         },
         {
            "date":"2013-11-19",
            "time":"12:20",
         }
      ]
   }
}

And it's my code at the moment:

public class json {
    public static void main(String[] args) throws IOException, ParseException {

        URL urlData = new URL("http://path.to/json");
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                urlData.openConnection().getInputStream(), "utf-8"));
        String struct = reader.readLine();

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(struct);
        JSONObject lev1 = (JSONObject) obj;
        System.out.println(lev1.get("date"));
    }
}

I got a date value (19.11.2013), but I don't know how to get child's values of date and time. I'm using json-simple library.

Answer

kiruwka picture kiruwka · Nov 19, 2013

Here is the idea :

JSONObject parent = (JSONObject) lev1.get("parent");
JSONArray child1 = (JSONArray) parent.get("child1"); // same for child2
for (Object elem : child1) {
    System.out.prinlnt("date =  " + ((JSONObject) elem).get("date"));
    System.out.prinlnt("time =  " + ((JSONObject) elem).get("time"));
}

Let me know if it does not compile, otherwise should work.