Saturday, 13 July 2013

How to utilize deserialize method to parse JSON object in sales force.

Parsing individual elements from  JSON object can be done from sales force Json Parser, but if the data in the Json Object is quite big then the parser will easily hit the script exception.

To parse a JSON Object with following structure can easily done a single line of code using deserialize method in Apex JSON class. But for that there should be an Object model to map the Json Object attributes into an apex Object.

Let's assume you have received a JSON Object in the below format.
 "kind": "calendar#events",
 "etag": "Some Text",
 "summary": "",
 "updated": "2013-07-11T08:09:37.786Z",
 "timeZone": "Asia/Calcutta",
 "accessRole": "owner",
 "defaultReminders": [
   "method": "email",
   "minutes": 10
   "method": "popup",
   "minutes": 30

To use deserialize method we need to have a class model to map the JSON Object data into class.
The class model for the above JSON Object is given below.

class Calender
 String kind;
 String etag ;
 String summary;
 String updated
 String timeZone;
 String accessRole,
 List<remainder> defaultReminders;
class remainder
     String method;
    String minutes;
The deserialize method map the JSON object properties into apex class properties by variable name, So the variable name in the class should match the Json Object attributes.

To map the JSON object into an apex object the deserialize method can be used as follows.
Calender c = (Calender)System.JSON.deserialize(JsonObjectBody,Calender.class);

The calender object c will receive all the attributes from Json Object.

No comments:

Post a Comment