Saturday, February 16, 2019

Apex JSON Generator

This post explains how to generate JSON using Apex.

Example:
Apex Class
public class GenerateJSONDemo {
    
    public static string jsonGeneratorSample() {
        String strJson = '';
        
        for(Account accIterator : [SELECT Id, Name, Industry, Phone, Type From Account limit 5]) {
            try {
                // Create a JSONGenerator object
                JSONGenerator jsGen = JSON.createGenerator(true);
                // start object ({)
                jsGen.writeStartObject();
                jsGen.writeFieldName('Account');
                jsGen.writeStartObject();
                jsGen.writeStringField('Id', accIterator.Id);
                jsGen.writeStringField('Name', accIterator.Name);
                jsGen.writeStringField('Industry', accIterator.Industry);
                jsGen.writeStringField('Phone', accIterator.Phone);
                jsGen.writeStringField('Account Type', accIterator.Type);
                // end object (})
                jsGen.writeEndObject();
                jsGen.writeEndObject();
                strJson = jsGen.getAsString(); 
            }
            catch(Exception ex) {
                System.debug('Line number ====> '+ex.getLineNumber() + 'Exception Message =====> '+ex.getMessage());   
            }
        }
        if(!String.isBlank(strJson)) {
            return strJson;
        }
        else {
            return null;
        }
    }
}

Result
{
 "Account" : {
  "Id" : "0017F00001V3WVzQAN",
  "Name" : "Emporium",
  "Industry" : "Biotechnology",
  "Phone" : "4567890321",
  "Account Type" : "Installation Partner"
 }
 }

Resource:
JSONGenerator Class

No comments:

Post a Comment