JSONGenerator in Apex

This class Contains methods used to serialize objects into JSON content using the standard JSON encoding. There are number of methods available to create a JSON string as per the request we want to generate for API.
The System.JSONGenerator class is provided to enable the generation of standard JSON-encoded content and gives you more control on the structure of the JSON output.

For the following JSON result type.

{
  "type": "Email",
  "templateName": "Basic Template 1",
  "locationID": "346345",
  "from": {
    "name": "Jane Smith",
    "email": "janesmith@gmail.com"
  },
  "to": {
    "name": "John Doe",
    "email": "johndoe@gmail.com",
    "phone": "6501235678"
  },
  "sourceIDs": [
    "FACEBOOK"
  ],
  "variables": [
    {
      "name": "recipient-name",
      "value": "John"
    },
    {
      "name": "recipient-last",
      "value": "Doe"
    }
  ]
}

The following is the code to generate above JSON

JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartObject();            
gen.writeStringField('type','Email');  
gen.writeStringField('templateName','Basic Template');             gen.writeStringField('locationID',346345);
gen.writeFieldName('from');
gen.writeStartObject();
gen.writeStringField('name', 'Jane Smith');
gen.writeStringField('email','janesmith@gmail.com');
gen.writeEndObject();
gen.writeFieldName('to');
gen.writeStartObject();
gen.writeStringField('name', 'John Doe');
gen.writeStringField('email', 'johndoe@gmail.com');
gen.writeStringField('phone', '6501235678');
gen.writeEndObject();
// for single variable
gen.writeFieldName('variables');
gen.writeStartArray();
gen.writeStartObject();
gen.writeStringField('name', 'recipient-name');
gen.writeStringField('value', 'John');
gen.writeEndObject();
gen.writeEndArray();
gen.writeFieldName('sourceIDs');
gen.writeStartArray();
gen.writeString('Salesforce');
gen.writeEndArray();
gen.writeEndObject();

For precise information about the JSON Click on the link .

Leave a comment