Friday, 9 August 2013

JSON Generator

JSONGenerator:
Since the JSON encoding that's generated by Apex through the serialization method in the System.JSON class isn't identical to the standard JSON encoding in some cases, the System.JSONGenerator class is provided to enable the generation of standard JSON-encoded content.
JSONGenerator Methods:
The following are instance methods of the System.JSONGenerator class.
Method
Description
close
Closes the JSON generator.No more content can be written after the JSON generator is closed.
getAsString
Returns the generated JSON content.
Also, this method closes the JSON generator if it isn't closed already.
isClosed
Returns true if the JSON generator is closed; otherwise, returns false.
writeBlob
Writes the specified Blob value as a base64-encoded string.
writeBlobField
Writes a field name and value pair using the specified field name and BLOB value.
writeBoolean
Writes the specified Boolean value.
writeBooleanField
Writes a field name and value pair using the specified field name and Boolean value.
writeDate
Writes the specified date value in the ISO-8601 format.
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.
writeDateTime
Writes the specified date and time value in the ISO-8601 format.
writeDateTimeField
Writes a field name and value pair using the specified field name and date and time value. The date and time 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 ('}').
writeFieldName
Writes a field name.
writeId
Writes the specified ID value.
writeIdField
Writes a field name and value pair using the specified field name and identifier value.
writeNull
Writes the JSON null literal value
writeNullField
Writes a field name and value pair using the specified field name and the JSON null literal value.
writeNumber
Writes the specified decimal value.
writeNumber
Writes the specified double value.
writeNumber
Writes the specified integer value.
writeNumber
Writes the specified long value.
writeNumberField

Writes a field name and value pair using the specified field name and decimal value.
writeNumberField
Writes a field name and value pair using the specified field name and double value.
writeNumberField
Writes a field name and value pair using the specified field name and integer value.
writeNumberField
Writes a field name and value pair using the specified field name and long value.
writeObject
Writes the specified Apex object in JSON format
writeObjectField
Writes a field name and value pair using the specified field name and Apex object.
writeStartArray
Writes the starting marker of a JSON array ('[').
writeStartObject
Writes the starting marker of a JSON object ('{').
writeString
Writes the specified string value.
writeStringField
Writes a field name and value pair using the specified field name and string value.
writeTime
Writes the specified time value in the ISO-8601 format.
writeTimeField
Writes a field name and value pair using the specified field name and time value in the ISO-8601 format.
Simple Example for JSONGenerator
JSONGenerator gen=JSON.createGenerator(true);
gen.writeStartObject(); //It is used for making starting object(‘{‘)
gen.writeStringField('Summary','Hyderabad');//Here it is used for making name ,value pair
gen.writeEndObject();//It is used for making end of object(‘}’)
System.debug('getAsString:'+gen.getAsString());

Output:
{
  "Summary" : "Hyderabad"
}
Example 2:
public  class GoogleCalendarEvent {
     public String id;
     public String htmlLink;
     public DateTime created;
     public String summary;
     public String description;
     public String location;
     public Integer sequence;
     public List<GoogleEventAttendee> attendees;
     public GoogleCalendarEvent(){
          this.id='EMP103';
          this.htmlLink='www.google.com';
          this.created=System.now();
          this.summary='Hi this is Balaji Malemarpuram';
          this.description='Hello Have a nice day';
          this.location='Hyderabad';
          this.sequence=2;
          attendees=new List<GoogleEventAttendee>();
          GoogleEventAttendee attend=new GoogleEventAttendee();
          attend.email='mbalaji105@gmail.com';
          attend.additionalGuests=10;
          attend.optional=true;
          attendees.add(attend);
          GoogleEventAttendee attend1=new GoogleEventAttendee();
          attend1.email='Sreevalli@gmail.com';
          attend1.additionalGuests=20;
          attend1.optional=true;
          attendees.add(attend1);
         
     }
     public Class GoogleEventAttendee{
      public String email;
      public boolean optional;
      public integer additionalGuests;
     }
     public  void generateJson(){
          JSONGenerator gen = JSON.createGenerator(true);
          gen.writeStartObject();
          gen.writeStringField('id',this.id);
          gen.writeDateTimeField('Created',this.created);
          gen.writeStringField('Summary',this.summary);
          gen.writeStringField('Description',this.description);
          gen.writeStringField('Location',this.location);
          gen.writeNumberField('Sequence',this.sequence);     
          gen.writeFieldName('attendees');
          gen.writeStartArray();
          //for each attendee create a JSON object
          for(GoogleEventAttendee gEventAttendee: this.attendees){
              gen.writeStartObject();
              gen.writeStringField('email', gEventAttendee.email);            
              gen.writeBooleanField('optional', gEventAttendee.optional);
              gen.writeNumberField('additionalGuests', gEventAttendee.additionalGuests);
              gen.writeEndObject();
          }
          gen.writeEndArray();
          gen.writeEndObject();
          //end of the parent JSON object  
          String jsonString = gen.getAsString();
          System.debug('jsonString:'+jsonString);
     }
}
Output:

{
  "id" : "EMP103",
  "Created" : "2013-06-13T08:59:44.949Z",
  "Summary" : "Hi this is Balaji Malemarpuram",
  "Description" : "Hello Have a nice day",
  "Location" : "Hyderabad",
  "Sequence" : 2,
  "attendees" : [ {
    "email" : "mbalaji105@gmail.com",
    "optional" : true,
    "additionalGuests" : 10
  }, {
    "email" : "Sreevalli@gmail.com",
    "optional" : true,
    "additionalGuests" : 20
  } ]
}

Example 3:

public  class JsonstringgeneratefromAccountdata {
     public void jsongenerate(){
          JSONGenerator gen = JSON.createGenerator(true);
          gen.writeString('Account Data');
          gen.writeStartArray();
          for(Account actobj:[select id,name,type,Industry from Account limit 2]){
              gen.writeStartObject();
                   gen.writeStringField('Account Name',actobj.Name);
                   gen.writeStringField('Account Type',actobj.Type);
                   gen.writeStringField('Industry',actobj.Industry);
              gen.writeEndObject();
          }
          gen.writeEndArray();
          System.debug('Json Account Structure:'+gen.getAsString());
     }
}
Output:
"Account Data" [ {
"Account  Name" : "ABCFoundation",
"Account  Type" : "Other",
"Industry" : "Engineering"
 } ,
 {
"Account  Name" : "CDEFoundation",
"Account  Type" : "Other",
"Industry" : "Agriculture"
 } ]