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] ------------------------------------------------------------------------