Hello friends, today we are going to discuss JSON Generator Apex Salesforce. JSON Generator class used to generate standard JSON-encoded content. You can build JSON content, element by element, using the standard JSON encoding. For this, we use the methods in the JSONGenerator class.
Also, check this: QuickBooks Integration With Salesforce Rest API
JSON Generator Class Key Methods:
- getAsString : Returns the generated JSON content, and also this method closes the JSON generator if it isn’t closed already.
- writeBlob(blobValue): Writes the specified Blob value as a base64-encoded string.
- writeBlobField(fieldName, blobValue):Writes a field name and value pair using the specified field name and BLOB value.
- writeBoolean(blobValue): Writes the Boolean value.
- writeEndArray() : Writes the ending marker of a JSON array (‘]’).
- writeEndObject() : Writes the ending marker of a JSON object (‘}).
- writeStartArray(): Writes the starting marker of a JSON array (‘[‘).
- writeStartObject() : Writes the starting marker of a JSON object (‘{‘).
- writeObject(anyObject) : Writes the specified Apex object in JSON format.
Check more methods: JSONGenerator Class
Code :
GenerateJSONData.cls : In this class we will fetch contact data and create JSON encode data.
public class GenerateJSONData {
public static void generateJSONFormatDataWithArray(){
JSONGenerator jsGen = JSON.createGenerator(true);
jsGen.writeStartObject();
jsGen.writeFieldName('ConatctData');
jsGen.writeStartArray();
for(Contact ct : [SELECT Id, FirstName, LastName, Email, Phone FROM Contact WHERE FirstName != '' AND Email!=null AND Phone !=null LIMIT 5]){
jsGen.writeStartObject();
jsGen.writeStringField('FirstName', ct.FirstName);
jsGen.writeStringField('LastName', ct.LastName);
jsGen.writeStringField('Email', ct.Email);
jsGen.writeStringField('Phone', ct.Phone);
jsGen.writeEndObject();
}
jsGen.writeEndArray();
jsGen.writeEndObject();
String jsonData = jsGen.getAsString();
System.debug('json format Data==> ' + jsonData);
}
public static void generateJSONFormatDataWithoutArray(){
JSONGenerator jsGen = JSON.createGenerator(true);
jsGen.writeStartObject();
for(Contact ct : [SELECT Id, FirstName, LastName, Email, Phone FROM Contact WHERE FirstName != '' AND Email!=null AND Phone !=null LIMIT 1]){
jsGen.writeFieldName('ConatctData');
jsGen.writeStartObject();
jsGen.writeStringField('FirstName', ct.FirstName);
jsGen.writeStringField('LastName', ct.LastName);
jsGen.writeStringField('Email', ct.Email);
jsGen.writeStringField('Phone', ct.Phone);
jsGen.writeEndObject();
}
jsGen.writeEndObject();
String jsonData = jsGen.getAsString();
System.debug('json format Data==> ' + jsonData);
}
}
OutPut :
With Array :
Wthout Array :
Reference :
What’s your Reaction?
+1
+1
+1
+1
+1
+1