Sunday, 14 December 2014

Generation of JSON String , Deserialize and Serialize

Hi,
We have a small example ,how to generate json .The below code is used for  generating json string.
To generate JSON string we have to use "JSONGenerator " and "createGenerator(true)" method.



JSONGenerator gen=JSON.createGenerator(true);
gen.writeStartArray();
gen.writeStartObject();
gen.writenumberField('StudentNumber',1);
gen.writeStringField('StudentName','Balaji');
gen.writeEndObject();
gen.writeStartObject();
gen.writenumberField('StudentNumber',2);
gen.writeStringField('StudentName','Shilpa');
gen.writeEndObject();
gen.writeEndArray();
String jsonString= gen.getAsString();
System.debug('jsonString:'+jsonString);

Output:
=====
jsonString:[ {
"StudentNumber" : 1,
"StudentName" : "Balaji"
 }, {
  "StudentNumber" : 2,
   "StudentName" : "Shilpa"
  } ]

To deserialize the above json string ,we have to prepare a class as shown below.
Class:
======
public class Studentscls{
    public Class StudentDetail{
        public integer StudentNumber{get;set;}
        public String StudentName{get;set;}  
    }
}

Execution:
------------
To deserialize JSON string we have "deserialize" method as shown below by using above class.

List<Studentscls.StudentDetail>  studentList = (List<Studentscls.StudentDetail>)JSON.deserialize(jsonString,List<Studentscls.StudentDetail>.class);
System.debug('Deserialized Result:'+studentList);

OuptPut:
======
Deserialized Result:(StudentDetail:[StudentName=Balaji, StudentNumber=1], StudentDetail:[StudentName=Shilpa, StudentNumber=2])

To serialize above list we have to user "serialize()" method as shown below.
--------------------------------------------------------------------------------------------

String studentJSONString=Json.serialize(studentList);
System.debug('Student JSONString:'+studentJSONString);

Output:
=====

Student JSONString:
[{"StudentNumber":1,"StudentName":"Balaji"},{"StudentNumber":2,"StudentName":"Shilpa"}]


No comments:

Post a Comment

Best Practices for Building Prompt Templates

 Hi, The following best practices should be considered when building prompt templates: Make sure that your prompt templates are concise and ...