Java get nested JSON object/array

DNC :

Code used:

jObj = new JSONObject(json);
newJSONString = jObj.getString("payload");
JArray = new JSONArray(newJSONString);

This is what JArray looks like:

[{"06:30:00":{"color":"grey","time_color":"black"},"06:45:00":{"color":"grey","time_color":"black"}}]

Now I want to loop through the received times and print their color, how to do this?

What I've tried:

for (int i = 0; i < JArray.length(); ++i) {
    JSONObject rec = null;
    try {
        rec = JArray.getJSONObject(i);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    android.util.Log.e("print row:", String.valueOf(rec));
}

This just gives me this output:

{"06:30:00":{"color":"grey","time_color":"black"},"06:45:00":{"color":"grey","time_color":"black"}}

CodeYourBrain :

You are getting this output since your JSON array contains only one JSON object which is - {"06:30:00":{"color":"grey","time_color":"black"},"06:45:00":{"color":"grey","time_color":"black"}}

Before answering your question, I would recommend you to go through JSON syntax. It will help you understand your question and answer effectively.

Coming back to your question, in order to get "color" field from your nested JSON:

  1. Traverse through keys in your JSON object. In your case these are - "06:30:00" , "06:45:00". You can google out solution to traverse through keys in JSON object in java.

  2. Get nested object associated with given key(time) - you can use getJSONObject() method provided by Json library for this.

  3. Get "color" field from json object - you can use optString() or getString() methods provided by Json library for this- depending upon whether your string is mandatory or optional.

Here is working solution in java for your problem:

public static void getColor(JSONObject payloadObject) {
    try {
        JSONArray keys = payloadObject.names();
        for (int i = 0; i < keys.length(); i++) {
            String key = keys.getString(i); // Here's your key
            JSONObject value = payloadObject.getJSONObject(key); // Here's your value - nested JSON object
            String color = value.getString("color");
            System.out.println(color);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Please note, it is considered that object you receive as payload is a JSON object.

Hope this helps.

Thanks.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=154621&siteId=1