Create JSON using apex

JSON Stands for JavaScript Object Notation. Creating JSON in Apex is not a Big Deal. If it’s just about serializing an object, the JSON class will be enough by itself.

Below is the Query that we can run from Execute Annoynmous block and check the output.

System.debug(JSON.serialize( [Select Id from Account limit 1] ));


This can be done using JSON Generator Class too. Below example is taken from Salesforce developer Guide.

public class JSONGeneratorSample{

    public class A { 
        String str;

        public A(String s) { str = s; }

    static void generateJSONContent() {
        // Create a JSONGenerator object.
        // Pass true to the constructor for pretty print formatting.
        JSONGenerator gen = JSON.createGenerator(true);

        // Create a list of integers to write to the JSON string.
        List<integer> intlist = new List<integer>();

        // Create an object to write to the JSON string.
        A x = new A('X');

        // Write data to the JSON string.
        gen.writeNumberField('abc', 1.21);
        gen.writeStringField('def', 'xyz');

        gen.writeObjectField('aaa', intlist);


        gen.writeFieldName('Object A');



        // Get the JSON string.
        String pretty = gen.getAsString();

        System.assertEquals('{\n' +
        '  "abc" : 1.21,\n' +
        '  "def" : "xyz",\n' +
        '  "ghi" : {\n' +
        '    "aaa" : [ 1, 2, 3 ]\n' +
        '  },\n' +
        '  "Object A" : {\n' +
        '    "str" : "X"\n' +
        '  }\n' +
        '}', pretty);

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s