Tuesday, 3 February 2015

JSON Deserialize


If Rest API returns the JSON string, below is the JSON String (array of data). if you have square bracket in your JSON then it is returning the array of the data.

String jsonString = '[ {
 "FirstName" : "test",
 "LastName" : "data1",
 "Email" : "test.data1@email.com",
 "Title" : "Mr"
 },
 {
 "FirstName" : "test",
 "LastName" : "data2",
 "Email" : "test.data2@email.com",
 "Title" : "Miss"
 },
 {
 "FirstName" : "test",
 "LastName" : "data3",
 "Email" : "test.data3@email.com",
 "Title" : "Mr"
 },
 {
  "FirstName" : "test",
 "LastName" : "data4",
 "Email" : "test.data4@email.com",
 "Title" : "Miss"
 },
 {
 "FirstName" : "test",
 "LastName" : "data5",
 "Email" : "test.data5@email.com",
 "Title" : "Mr"
 } ] ';

we have to create wrapper class to get or store the values from API.

Wrapper class :
global class wrapperclass_For_API
 {
        public string Firstname{get;set;} // case sensitive we have to give the name as there in JSON.
        public string Lastname{get;set;}
        public string Email{get;set;}
        public string Title{get;set;}       
}

In Apex class the below code can be used to get the JSON without parsing.

 List<wrapperclass_For_API> rs = (List<wrapperclass_For_API>)System.JSON.deserialize(jsonString, List<wrapperclass_For_API>.class);
List<wrapperclass_For_API> wrapperlist = new List<wrapperclass_For_API>();
// If we want to get the data, we can directly get the data from rs variable like below.
for(wrapperclass_For_API s : rs)
{
       wrapperclass_For_API wfa = new wrapperclass_For_API();
       wfa.Firstname = s.Firstname;
       wfa.Lastname = s.Lastname;
       wfa.Email = s.Emaill;
       wfa.Title = s.Title;
       wrapperlist.add(wfa);
}
// after that we can access the values through wrapper list.

If JSON string is not an array, it returns only single user data based on email Id as below

string JSON_string = {
  "FirstName" : "test",
 "LastName" : "data5",
 "Email" : "test.data5@email.com",
 "Title" : "Mr"
}

   Map<String, Object> m = (Map<String, Object>) JSON.deserializeUntyped(JSON_string);
   Object First_Name = (Object) m.get('FristName'); 
   system.debug('**********'+First_Name); // it returns "test"(value of the first name) in the log.
  

No comments:

Post a Comment