Java
Chilkat2 Java
JSON: Nested Objects
See more JSON Examples
Here we have a JSON object that contains nested JSON objects. This example demonstrates how to access the contents of the nested objects.
{
"name": "donut",
"image":
{
"fname": "donut.jpg",
"w": 200,
"h": 200
},
"thumbnail":
{
"fname": "donutThumb.jpg",
"w": 32,
"h": 32
}
}
Chilkat Java Downloads
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;
public class ChilkatExample {
public static void main(String[] args) {
JsonObject json = new JsonObject();
// This is the above JSON with whitespace chars removed (SPACE, TAB, CR, and LF chars).
// The presence of whitespace chars for pretty-printing makes no difference to the Load
// method.
String jsonStr = "{\"name\": \"donut\",\"image\":{\"fname\": \"donut.jpg\",\"w\": 200,\"h\": 200},\"thumbnail\":{\"fname\": \"donutThumb.jpg\",\"w\": 32,\"h\": 32}}";
try {
json.load(jsonStr);
} catch (ChilkatException e) {
System.out.println(e.getLastErrorText());
return;
}
// Get the "image" object.
JsonObject imageObj = new JsonObject();
json.objectOf2("image", imageObj);
System.out.println("image: fname=" + imageObj.stringOf("fname") + ", width=" + imageObj.intOf("w") + ", height=" + imageObj.intOf("h"));
// Get the "thumbnail" object.
JsonObject thumbObj = new JsonObject();
json.objectOf2("thumbnail", thumbObj);
System.out.println("thumbnail: fname=" + thumbObj.stringOf("fname") + ", width=" + thumbObj.intOf("w") + ", height=" + thumbObj.intOf("h"));
}
}