Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

JSON: Miscellaneous Operations

See more JSON Examples

Demonstrates a variety of JSON API methods. This example uses the following JSON document:
{
   "alphabet": "abcdefghijklmnopqrstuvwxyz",
   "sampleData" : {
           "pi": 3.14,
	   "apple": "juicy",
	   "hungry": true,
	   "withoutValue": null,
           "answer": 42
          
	}
}

Chilkat Java Downloads

Chilkat2 Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.JsonObject;

public class ChilkatExample {

    public static void main(String[] args) {
        JsonObject json = new JsonObject();
        json.setEmitCompact(false);

        // Assume the file contains the data as shown above..
        try {
            json.loadFile("qa_data/json/sample2.json");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Get the "sampleData" object:
        JsonObject sampleData = new JsonObject();
        json.objectOf2("sampleData", sampleData);

        // Demonstrate BoolAt and BoolOf
        System.out.println("hungry: " + sampleData.boolOf("hungry"));
        System.out.println("hungry: " + sampleData.boolAt(2));

        // StringOf returns the value as a string regardless of it's actual type:
        System.out.println("pi: " + sampleData.stringOf("pi"));
        System.out.println("answer: " + sampleData.stringOf("answer"));
        System.out.println("withoutValue: " + sampleData.stringOf("withoutValue"));
        System.out.println("hungry: " + sampleData.stringOf("hungry"));

        // Demonstrate IsNullOf / IsNullAt
        System.out.println("withoutValue is null? " + sampleData.isNullOf("withoutValue"));
        System.out.println("withoutValue is null? " + sampleData.isNullAt(3));
        System.out.println("apple is null? " + sampleData.isNullOf("apple"));
        System.out.println("apple is null? " + sampleData.isNullAt(1));

        // IntOf
        System.out.println("answer: " + sampleData.intOf("answer"));

        // SetNullAt, SetNullOf
        // Set "pi" to null
        sampleData.setNullAt(0);
        // Set "answer" to null
        sampleData.setNullOf("answer");

        // Show the changes:
        System.out.println(json.emit());

        // Restore pi and apple:
        sampleData.setNumberAt(0, "3.14");
        sampleData.setNumberOf("answer", "42");

        // Show the changes:
        System.out.println(json.emit());

        // Add a null value named "afterApple" just after "apple"
        sampleData.addNullAt(2, "afterApple");

        // Add a boolean value just after "pi"
        sampleData.addBoolAt(1, "afterPi", false);

        // Examine the changes..
        System.out.println(json.emit());
    }
}