JSON To apex

Here in this post  we learn how one can  Handle json in  Apex code or how you can handle jsonstring in apex .

We need to convert json coming from rest api to perform some operation in apex .

So To do this we can use one of the following methods .

  1.  Convert JSON To Apex Map
  2.  Convert  JSON To Apex Wrapper class
  3.  We can use Parser Class method to parse json .

Lets  understand above points with help of an Example.

Here is our json example .

 


 String jsonData = {name: “John”, age: 31, city: “New York”};

We use this json in all example 


  1.  Convert JSON To apex Map

You Can easily Convert Json to Apex Map by using JSON.deserializeUntyped

Map<String, Object> resMap =   (Map<String, Object>)JSON.deserializeUntyped(jsonData);

2 . Convert  JSON to apex Wrapper class

Use JSON.deserialize method  to convert json into wrapper. you can use JSON.deserialize to convert json into any type you want.

jsonWrapper Jsondatawrapper = (jsonWrapper)JSON.deserialize(jsonData,jsonWrapper.class)

To Use this method you need to create a wrapper class first.

Wrapper class  : 

public class jsonWrapper
{

// here rows is the name of field in json this variable should be
public string name ;
public string state;
public string city ; 

}

 

Now Convert jsonString to wrapper class .

jsonWrapper Jsondatawrapper = (jsonWrapper)JSON.deserialize(jsonData,jsonWrapper.class);

You can easily use wrapper class like this .

system.debug(‘value of name is ‘+Jsondatawrapper.name);

system.debug(‘value of state is ‘+Jsondatawrapper.state);

system.debug(‘value of city is ‘+Jsondatawrapper.city);

3 . Use the Json Parser Class methods to Parse JSON-Encoded Content.

you can also use json parser class  like below example to get values from json string .

 

JSONParser parser = JSON.createParser(jsonData);
parser.nextToken();// token  parser
parser.nextValue(); // value paser
if (parser.getCurrentName() == 'City') 
{

    String city = parser.getText(); 
    system.debug('value of city is '+city);
    parser.nextToken();
    parser.nextValue();
}

 

Hits: 1170

Share Post

By Himanshu Rana

My Name is Himanshu Rana, 23 Years young, born and grow up in Ghaziabad, India. A High Spirited Salesforce Admin, Developer and a Blogger. I currently work at Wakencode Technologies,

Leave a Reply

Your email address will not be published. Required fields are marked *