Salesforce Apex JSON Generator

We can generate standard JSON-encoded content, using the JSONGenerator class methods.

JSONGenerator Class Methods:

Method Description
close Closes the JSON generator.No more content can be written after the JSON generator is closed.
getAsString Returns the generated JSON content, and also this method closes the JSON generator if it isn’t closed already.
isClosed Returns true if the JSON generator is closed; otherwise, returns false.
writeBlob Writes the specified Blob value as a base64-encoded string.
writeBlobField Writes a field name and value pair using the specified field name and BLOB value.
writeBoolean Writes the specified Boolean value.
writeBooleanField Writes a field name and value pair using the specified field name and Boolean value.
writeDate Writes the specified date value in the ISO-8601 format.
writeDateField Writes a field name and value pair using the specified field name and date value. The date value is written in the ISO-8601 format.
writeDateTime Writes the specified date and time value in the ISO-8601 format.
writeDateTimeField Writes a field name and value pair using the specified field name and date and time value. The date and time value is written in the ISO-8601 format.
writeEndArray Writes the ending marker of a JSON array (‘]’).
writeEndObject Writes the ending marker of a JSON object (‘}’).
writeFieldName Writes a field name.
writeId Writes the specified ID value.
writeIdField Writes a field name and value pair using the specified field name and identifier value.
writeNull Writes the JSON null literal value
writeNullField Writes a field name and value pair using the specified field name and the JSON null literal value.
writeNumber Writes the specified decimal, double, integer and long value.
writeNumberField Writes a field name and value pair using the specified field name and decimal, double, integer, long value.
writeObject Writes the specified Apex object in JSON format
writeObjectField Writes a field name and value pair using the specified field name and Apex object.
writeStartArray Writes the starting marker of a JSON array (‘[‘).
writeStartObject Writes the starting marker of a JSON object (‘{‘).
writeString Writes the specified string value.
writeStringField Writes a field name and value pair using the specified field name and string value.
writeTime Writes the specified time value in the ISO-8601 format.
writeTimeField Writes a field name and value pair using the specified field name and time value in the ISO-8601 format.

Example:

List<Account> accList = [SELECT Id, Name, AccountNumber, Industry From Account];

if(!accList.isEmpty()){
    JSONGenerator gen = JSON.createGenerator(true);
    gen.writeStartObject();     
    gen.writeFieldName('AccountList');
    gen.writeStartArray();
    for(Account acc :accList){
        gen.writeStartObject();
        gen.writeStringField('Id', acc.Id);
        gen.writeStringField('Name', acc.Name);
        gen.writeStringField('AccountNumber', acc.AccountNumber);
        gen.writeStringField('Industry', acc.Industry);
        gen.writeEndObject();
    }
    gen.writeEndArray();
    gen.writeEndObject();
    String jsonData = gen.getAsString();
    System.debug('jsonData-' + jsonData);
}

Output:

{
  "AccountList" : [ {
    "Id" : "001B000000oAg2fIAC",
    "Name" : "Bostonic Bulk Company",
    "AccountNumber" : "232323",
    "Industry" : "Technology"
  }, {
    "Id" : "001B000000oAg4UIAS",
    "Name" : "Bitrex Bulk Company",
    "AccountNumber" : "123232",
    "Industry" : "Technology"
  }, {
    "Id" : "001B000000pA7skIAC",
    "Name" : "Amazon",
    "AccountNumber" : "12345",
    "Industry" : "Technology"
  }, {
    "Id" : "001B000000pA7sVIAS",
    "Name" : "Salesforce",
    "AccountNumber" : "12346",
    "Industry" : "Technology"
  } ]
}

  • Pankaj Amrutkar

    Hello Biswajeet,

    I have used the JSONGenerator class I have tested on postman but in response backslash gets added into the json.
    “{“Id”:”a171j000000WDQCAA4″,”Name”:”Q-00123″}”
    Could you please suggest me how can I generate the Json response without the backslash.

    Thanks you

    • Wes Nolte

      That's a JSON string, you need to parse it from a string into actual JSON (which is what .getAsString() returns). In JavaScript (you could do this in your browser console) you'd use JSON.parse(). And if you wanted to convert the other way you'd use something like this .

  • Suma latha

    Hello Biswajeet,

    i have a requirement to create JSON Dynamically from APEX. i just used your code above and i am ending up with some error.
    “System.NullPointerException: null argument for JSONGenerator.writeStringField()”

    can you please check this

    Thank you.

    • Priya Chatelli

      If data on any of the fields is null, you would get this exception. Make sure there is data or handle to write only the records that has data in this field