Sample code for 30+ languages & platforms
Android™

Create a JSON Array of Objects

See more JSON Examples

Demonstrates how to create a JSON array of objects.

Chilkat Android™ Downloads

Android™
// 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;

    CkJsonArray arr = new CkJsonArray();

    CkJsonObject obj = new CkJsonObject();

    // Create a new and empty JSON object in the 1st position of the JSON array 
    // and return the reference in the last argument.
    arr.AddObjectAt2(0,obj);
    obj.UpdateString("Name","Otto");
    obj.UpdateInt("Age",29);
    obj.UpdateBool("Married",false);

    // Create a new and empty JSON object in the 2nd position of the JSON array 
    // and return the reference in the last argument.
    arr.AddObjectAt2(1,obj);
    obj.UpdateString("Name","Connor");
    obj.UpdateInt("Age",43);
    obj.UpdateBool("Married",true);

    // Create a new and empty JSON object in the 3rd position of the JSON array 
    // and return the reference in the last argument.
    arr.AddObjectAt2(2,obj);
    obj.UpdateString("Name","Ramona");
    obj.UpdateInt("Age",34);
    obj.UpdateBool("Married",true);

    // Examine what we have:
    arr.put_EmitCompact(false);
    Log.i(TAG, arr.emit());

    // The output is:

    // [
    //   {
    //     "Name": "Otto",
    //     "Age": 29,
    //     "Married": false
    //   },
    //   {
    //     "Name": "Connor",
    //     "Age": 43,
    //     "Married": true
    //   },
    //   {
    //     "Name": "Ramona",
    //     "Age": 34,
    //     "Married": true
    //   }
    // ]

  }

  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."
  }
}