JSONGenerator Class some frequently used Methods:
Method Description
getAsString Returns the generated JSON content, and also this method closes the JSON generator if it isn’t closed already.
writeBooleanField Writes a field name and value pair using the specified field name and Boolean value.
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.
writeEndArray Writes the ending marker of a JSON array (‘]’).
writeEndObject Writes the ending marker of a JSON object (‘}’).
writeNullField Writes a field name and value pair using the specified field name and the JSON null literal value.
writeNumberField Writes a field name and value pair using the specified field name and decimal, double, integer, long value.
writeStartArray Writes the starting marker of a JSON array (‘[‘).
writeStartObject Writes the starting marker of a JSON object (‘{‘).
writeStringField Writes a field name and value pair using the specified field name and string value.
{
"ContactList" : [ {
"ID" : "0032v00002j3qBCAAY",
"FirstName" : "Bhole",
"LastName" : "Shankar",
}, {
"ID" : "0032v00002j3qBDAAY",
"FirstName" : "Brajesh",
"LastName" : "Jha",
} ]
}
public class JSONContacts {
public static void JSONContactsMethod (){
List<Contact> conList = [SELECT ID, firstName, lastName FROM Contact];
if(conList.size()>0){
JSONGenerator jsonGen = JSON.createGenerator(true);
jsonGen.writeStartObject();
jsonGen.writeFieldName('ContactList');
jsonGen.writeStartArray();
for(Contact con : conList){
jsonGen.writeStartObject();
jsonGen.writeStringField('ID',con.Id);
jsonGen.writeStringField('FirstName',con.firstName);
jsonGen.writeStringField('LastName',con.lastName);
jsonGen.writeEndObject();
}
jsonGen.writeEndArray();
jsonGen.writeEndObject();
String jsonData = jsonGen.getAsString();
System.debug('Json Data = ' + jsonData);
}
}
}
How do you handle null values? This will break very fast in the real world.
ReplyDeletewriteNull Writes the JSON null literal value
DeletewriteNullField Writes a field name and value pair using the specified field name and
the JSON null literal value.