JSON Generator

What is JSONGenerator?


  • JSONGenerator class methods allows you can generate standard JSON-encoded content.
  • It allows to construct JSON content, element by element, using the standard JSON encoding.
  • Various methods are provided in the JSONGenerator class.
In this post, various JSONGenerator class methods will be explained along with a sample JSON and the class to built the JSON-encoded content. 

Below are few important methods that will be used frequently

writeStartObject - Writes the starting marker of JSON object - {
writeEndObject - Writes the ending marker of JSON object - }
writeStartArray - Writes the starting marker of JSON Array - [
writeEndArray - Writes the starting marker of JSON Array - ]
writeFieldName - Writes the field name in the JSON
writeStringField - Writes the field name and the value pair using the specified field and string value
writeNumberField - Write the field name and the value pair using the specified field and number value.
getAsString - Returns the written JSON string

For more information on the JSONGenerator follow the below links

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsongenerator.htm
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_System_JsonGenerator.htm

Let us consider the below JSON structure and query the account record to build this JSON using the JSONGenerator class.







Comments

Popular Posts