Custom JSON Object in Salesforce

Create a Custom JSON in  apex code

Apex is the coding language for Salesforce cloud computing.

Salesforce provides a Class ‘JSONGenerator’ using which one can serialize a collection, wrapper class into JSON or can deserialize in reverse.

Using this class a Custom JSON can also be written, below is the code snippet for the same:

JSONGenerator jsonObj = JSON.createGenerator(true);
        jsonObj.writeStringField('Container', 'Outer');
                jsonObj.writeStringField('innerWrapper1', 'Value1');
                jsonObj.writeStringField('innerWrapper2', 'Value2');
                jsonObj.writeStringField('innerWrapper3', 'Value3');
String finalJSON = jsonObj.getAsString();

The output of the above snippet when debugged will give:

'{"Container" : "Outer", 
  "Wrapper" : [ {  "innerWrapper1" : "Value1",  
                   "innerWrapper2" : "Value2",  
                   "innerWrapper3" : "Value3"
              } ]

Decoding each method of the JSONGenerator class:

  1. writeStartObject    : This creates the start of the outermost object ‘{‘
  2. writeStringField    : This creates the key-value pair
  3. writeFieldName      : This creates key for an inner object
  4. writeStartArray     : This creates start of an inner object ‘[‘
  5. writeEndArray       : This creates end of an inner object ‘]’
  6. writeEndObject      : This creates the end of the outermost object ‘}’
  7. getAsString         : This returns a the JSON created as String type

Happy Coding 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s