+ Start a Discussion
anil Kumaranil Kumar 

JSON Body in Apex

Hi All,

I would like to prepare dynamic JSON body for all the contact records with masked values like below mentioned format. If contact field value is exist in need to send it as True, if it is not exist send it as False. How to achieve this apex.

  "Name": "True",
  "LastName": "True",

  "Name": "False",
  "LastName": "True",


Anil Kumar
Raj VakatiRaj Vakati
Hi ,

Here is the sample code, Please modify as per your JSON object.
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStringField('Id', '1234');
gen.writeStringField('Name', 'Welcome');
gen.writeStringField('LastName', 'Hello');
gen.writeStringField('Phone', false);
gen.writeStringField('Phone', true);


String pretty = gen.getAsString().replace('\n', '');

Purushotham YellankiPurushotham Yellanki
Hi Anil, 

There are two ways you can form JSON. One is using JSON Generator Method and other would be using JSON Serializer (for this we creat a Wrapper Class). Above code is perfeclty fine with just one simple change like if you want to use boolean values then its better if we use writeBooleanField (Refere to JSONGenerator Class (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_System_JsonGenerator.htm)).

List<Contact> lstCnts = [Select Id, Name, LastName, OtherAddress, MailingAddress, Phone From Contact];

Lets say if above is your Contact List, then you can form JSON as below using JSONGenerator

String jsonBody;

if (lstCnts.size()>0) {
    JSONGenerator jsonGen = JSON.createGenerator(true);
    for (Contact c: lstCnts) {
        jsonGen.writeStringField('Id', c.Id);
        jsonGen.writeStringField('Name', c.Name);
        jsonGen.writeStringField('LastName', c.LastName);
        jsonGen.writeStringField('MailingAddress', String.ValueOf(c.OtherAddress));
        jsonGen.writeStringField('MailingAddress', String.ValueOf(c.MailingAddress));
        if (c.Phone != null) {
            jsonGen.writeBooleanField('Phone', True);
        } else {
            jsonGen.writeBooleanField('Phone', False);    
        jsonBody = jsonGen.getAsString();
        System.debug('************JSON BODY************' + jsonBody);

Also make sure your fields (OtherAddress, MailingAddress) return some values other wise you will end up hitting "System.NullPointerException: null argument for JSONGenerator.writeStringField()"!