Android™
Android™
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 Android™ Downloads
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;
import android.app.Activity;
import com.chilkatsoft.*;
import android.widget.TextView;
import android.os.Bundle;
public class SimpleActivity extends Activity {
private static final String TAG = "Chilkat";
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean success = false;
CkJsonObject json = new CkJsonObject();
// 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}}";
success = json.Load(jsonStr);
if (success == false) {
Log.i(TAG, json.lastErrorText());
return;
}
// Get the "image" object.
CkJsonObject imageObj = new CkJsonObject();
json.ObjectOf2("image",imageObj);
Log.i(TAG, "image: fname=" + imageObj.stringOf("fname") + ", width=" + String.valueOf(imageObj.IntOf("w")) + ", height="
+ String.valueOf(imageObj.IntOf("h")));
// Get the "thumbnail" object.
CkJsonObject thumbObj = new CkJsonObject();
json.ObjectOf2("thumbnail",thumbObj);
Log.i(TAG, "thumbnail: fname=" + thumbObj.stringOf("fname") + ", width=" + String.valueOf(thumbObj.IntOf("w"))
+ ", height=" + String.valueOf(thumbObj.IntOf("h")));
}
static {
System.loadLibrary("chilkat");
// Note: If the incorrect library name is passed to System.loadLibrary,
// then you will see the following error message at application startup:
//"The application <your-application-name> has stopped unexpectedly. Please try again."
}
}