2

I would like to parse netsted json in Java: Below is json string:

[
    {
        "id": 1,
        "empid": "12345",
        "details": {
            "name": "xyz",
            "age": "30",
            "sex": "M",
            "Address": {
                "Office": "office",
                "Home": "Home"
            }
        },
        "abcDetails": "asdf",
        "mobile": 123455
    },
    {
        "id": 2,
        "empid": "64848",
        "details": {
            "name": "eryje",
            "age": 3027,
            "sex": "M",
            "Address": {
                "Office": "office",
                "Home": "Home"
            }
        },
        "abcDetails": "fhkdl",
        "mobile": 389928
    }
]

I need name, age details from above json, can someone help how to parse these value in java, i tried the below code to get those value - it seems its nested and not sure how to get those value.

        JSONArray jsonarray = new JSONArray(str);
        for (int i = 0; i < jsonarray.length(); i++) {
            JSONObject obj1 = jsonarray.getJSONObject(i);

            String name = obj1.getString("name");
            String age = obj1.getString("age");

            System.out.println(name);
            System.out.println(age);
        }
4
  • so what is happening? Commented Jul 17, 2015 at 1:24
  • Why you dont try to parse JSON using this library: code.google.com/p/json-simple. :) Commented Jul 17, 2015 at 1:25
  • @LeoAguilar Look like he is already using an library Commented Jul 17, 2015 at 1:27
  • I'm getting this exception - if I try to use getString("name") - org.json.JSONException: JSONObject["name"] not found. at org.json.JSONObject.get(JSONObject.java:498) at org.json.JSONObject.getString(JSONObject.java:669) Commented Jul 17, 2015 at 1:31

4 Answers 4

1

You probably need to use #getJSONObject() for getting nested object.

  • But, this is my personal impression, why org.json package's version strings are date format ? Probably it's not good library...

Example:

package testing;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Hello world!
 */
public class App {

    static String json = ""
 + "["
 + " {"
 + "     \"id\": 1,"
 + "     \"empid\": \"12345\","
 + "     \"details\": {"
 + "         \"name\": \"xyz\","
 + "         \"age\": \"30\","
 + "         \"sex\": \"M\","
 + "         \"Address\": {"
 + "             \"Office\": \"office\","
 + "             \"Home\": \"Home\""
 + "         }"
 + "     },"
 + "     \"abcDetails\": \"asdf\","
 + "     \"mobile\": 123455"
 + " },"
 + " {"
 + "     \"id\": 2,"
 + "     \"empid\": \"64848\","
 + "     \"details\": {"
 + "         \"name\": \"eryje\","
 + "         \"age\": 3027,"
 + "         \"sex\": \"M\","
 + "         \"Address\": {"
 + "             \"Office\": \"office\","
 + "             \"Home\": \"Home\""
 + "         }"
 + "     },"
 + "     \"abcDetails\": \"fhkdl\","
 + "     \"mobile\": 389928"
 + " }"
 + "]";

    public static void main(String[] args) throws Exception {

        JSONArray jsonarray = new JSONArray(json);
        System.out.println(String.format("JSONArray length => %d", jsonarray.length()));

        for (int i = 0; i < jsonarray.length(); i++) {
            JSONObject obj1 = jsonarray.getJSONObject(i);
            JSONObject details = obj1.getJSONObject("details");
            System.out.println(String.format("details => %s", details.toString()));

            String name = details.getString("name");
            int age = details.getInt("age");
            System.out.println(name);
            System.out.println(age);
        }
    }
}

Results:

$ mvn exec:java -Dexec.mainClass="testing.App"
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building testing 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> exec-maven-plugin:1.2.1:java (default-cli) @ testing >>>
[INFO]
[INFO] <<< exec-maven-plugin:1.2.1:java (default-cli) @ testing <<<
[INFO]
[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ testing ---
JSONArray length => 2
details => {"sex":"M","Address":{"Home":"Home","Office":"office"},"age":"30","name":"xyz"}
xyz
30
details => {"sex":"M","Address":{"Home":"Home","Office":"office"},"age":3027,"name":"eryje"}
eryje
3027
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.576s
[INFO] Finished at: Fri Jul 17 10:46:29 JST 2015
[INFO] Final Memory: 7M/106M
[INFO] ------------------------------------------------------------------------
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you! It works. But I've scenario like some time i'll get the json without "details" object also.. Like below - [ { "id": 1, "empid": "12345", "details": { "name": "xyz", "age": "30", "sex": "M", "Address": { "Office": "office", "Home": "Home" } }, "abcDetails": "asdf", "mobile": 123455 }, { "id": 2, "empid": "64848", "abcDetails": "fhkdl", "mobile": 389928 } ] In this case - how to handle it?
@learnjava See also javadoc of #keys or #has. Probably, you should check JSON keys before getting it. If key doesn't exist, you call continue statement in for loop.
1

The property name and age are in the details Try this code

JSONArray jsonarray = new JSONArray(str);
        for (int i = 0; i < jsonarray.length(); i++) {
            JSONObject obj1 = jsonarray.getJSONObject(i);
            JSONObject details = obj1.getJSONObject("details");
            String name = details.getString("name");
            String age = details.getString("age");

            System.out.println(name);
            System.out.println(age);
        }

Comments

0

In your code your are doing

String name = obj1.getString("name");

but name is a sub-element of detail so you need to get the detail object first.

JSONObject detail = obj1.getJSONObject("details");

and then

String name = detail.getString("name");

2 Comments

Thanks for the response. But i've scenario sometime I wont receive "details" object like this - [ { "id": 1, "empid": "12345", "details": { "name": "xyz", "age": "30", "sex": "M", "Address": { "Office": "office", "Home": "Home" } }, "abcDetails": "asdf", "mobile": 123455 }, { "id": 2, "empid": "64848", "abcDetails": "fhkdl", "mobile": 389928 } ] - How to handle this scenario
wrap in up in an try/catch block catching the JSONException see json.org/javadoc/org/json/…
0
//import java.util.ArrayList;
//import org.bson.Document;

Document root= Document.parse("{\"records\":[\n" +
"    {\n" +
"        \"id\": 1,\n" +
"        \"empid\": \"12345\",\n" +
"        \"details\": {\n" +
"            \"name\": \"xyz\",\n" +
"            \"age\": \"30\",\n" +
"            \"sex\": \"M\",\n" +
"            \"Address\": {\n" +
"                \"Office\": \"office\",\n" +
"                \"Home\": \"Home\"\n" +
"            }\n" +
"        },\n" +
"        \"abcDetails\": \"asdf\",\n" +
"        \"mobile\": 123455\n" +
"    },\n" +
"    {\n" +
"        \"id\": 2,\n" +
"        \"empid\": \"64848\",\n" +
"        \"details\": {\n" +
"            \"name\": \"eryje\",\n" +
"            \"age\": 3027,\n" +
"            \"sex\": \"M\",\n" +
"            \"Address\": {\n" +
"                \"Office\": \"office\",\n" +
"                \"Home\": \"Home\"\n" +
"            }\n" +
"        },\n" +
"        \"abcDetails\": \"fhkdl\",\n" +
"        \"mobile\": 389928\n" +
"    }\n" +
"]}");


System.out.println((((Document)((ArrayList)root.get("records")).get(0)).get("id")));
System.out.println(((String)((Document)((ArrayList)root.get("records")).get(0)).get("empid")));
System.out.println(((String)((Document)((Document)((ArrayList)root.get("records")).get(0)).get("details")).get("name")));
System.out.println(((String)((Document)((Document)((ArrayList)root.get("records")).get(0)).get("details")).get("age")));
System.out.println(((String)((Document)((Document)((ArrayList)root.get("records")).get(0)).get("details")).get("sex")));
System.out.println(((String)((Document)((Document)((Document)((ArrayList)root.get("records")).get(0)).get("details")).get("Address")).get("Office")));
System.out.println(((String)((Document)((Document)((Document)((ArrayList)root.get("records")).get(0)).get("details")).get("Address")).get("Home")));
System.out.println(((String)((Document)((ArrayList)root.get("records")).get(0)).get("abcDetails")));
System.out.println((((Document)((ArrayList)root.get("records")).get(0)).get("mobile")));
System.out.println((((Document)((ArrayList)root.get("records")).get(1)).get("id")));
System.out.println(((String)((Document)((ArrayList)root.get("records")).get(1)).get("empid")));
System.out.println(((String)((Document)((Document)((ArrayList)root.get("records")).get(1)).get("details")).get("name")));
System.out.println((((Document)((Document)((ArrayList)root.get("records")).get(1)).get("details")).get("age")));
System.out.println(((String)((Document)((Document)((ArrayList)root.get("records")).get(1)).get("details")).get("sex")));
System.out.println(((String)((Document)((Document)((Document)((ArrayList)root.get("records")).get(1)).get("details")).get("Address")).get("Office")));
System.out.println(((String)((Document)((Document)((Document)((ArrayList)root.get("records")).get(1)).get("details")).get("Address")).get("Home")));
System.out.println(((String)((Document)((ArrayList)root.get("records")).get(1)).get("abcDetails")));
System.out.println((((Document)((ArrayList)root.get("records")).get(1)).get("mobile")));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.