Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

Since, the names of the array are child1 and child2 (which means the names are different), inside the parent object , first you have to fetch these names, and then for each array, fetch date and time.

Here struct , is the jsonString:

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(struct);
        JSONObject lev1 = (JSONObject) obj;
        Object jObj = lev1.get("parent");
        List keys = new ArrayList();
        if (jObj instanceof Map) {
            Map map = (Map) jObj;
            Set keySet = map.keySet();
            for (Object s : keySet) {
                JSONObject jsonObj = (JSONObject) jObj;
                JSONArray jarr = (JSONArray) jsonObj.get(s.toString());
                for (int i = 0; i < jarr.size(); i++) {
                    Object get = jarr.get(i);
                    JSONObject job = (JSONObject) get;
                    String date = job.get("date").toString();
                    String time = job.get("time").toString();
                    System.out.println("Date: " + date + " , Time: " + time);
                }
            }
        }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top