+ Start a Discussion
Vishnu Prasad 18Vishnu Prasad 18 

Difference between JSON Parser and JSON Deserialization

Hi,

 I am working on one of the requirement where I am receiving JSON string in the response. I am confused whether to use JSON Parser or JSON Deserialization. Can someone provide some details about these 2 methods to extract the value from JSON string. 

Thanks,
  Vishnu
Nithesh NNithesh N
In my Opinion, I would Use JSON Deserialization without any second thought.

If you use JSON Parser method, you need to parse JSON manually. Check the below sample code for example.
jsonStr = '{//some JSON data}'
JSONParser parser = JSON.createParser(jsonStr);
String text = '';
while (parser.nextToken() != null) {
   if(parser.getCurrentToken() == JSONToken.START_OBJECT){
      parser.nextToken();
      text = parser.getText() + ', ' + text;
      }
    //System.debug(parser.getText() + parser.nextToken() + ' - ' + parser.getText());
    if (parser.getCurrentToken() == JSONToken.START_ARRAY) {
        //parser.nextToken();
        text = parser.getText() + ', ' + text;
        }
}

By using JSON Deserialization, It is as simple as this.
<Class/Object> n = (<Class/Object>)JSON.deserialize('JSON', <Class/Object>.class);
<Class/Object> is the Apex Class for parsing a JSON structure
For this, first we need to create a class or an Inner class, which would contain all the variables that are to be stored from the JSON.

The JSON2Apex is a very handy tool for this. Go to http://json2apex.herokuapp.com/ and paste the JSON String in the space provided, and click on create Apex.

This would give you a class with member variables from the JSON String. You can just use this class as is or you can paste it into your existing class like an inner class.

You then use the JSON.de-serialize to parse the JSON.

Please do nor forget to mark this thread as SOLVED and answer as the BEST ANSWER if it helps address your issue.

Best,
Nithesh
Vishnu Prasad 18Vishnu Prasad 18
Hi Nitesh,

Thanks for the quick response. So, If I have understood it correctly, JSON Parser passes each and every element/token whereas using desrialization, we can get exact value of particular tag easily.

Thanks,
  Vishnu
Nithesh NNithesh N
By using JSON Deserialization, It deserializes that JSON response in to an Apex Object. So, After deserialization. 
<Class/Object> ResponseObject = (<Class/Object>)JSON.deserialize('JSON', <Class/Object>.class);
So, you would get that json data as Object and can access json elements as object elements. 

Please do nor forget to mark this thread as SOLVED and answer as the BEST ANSWER if it helps address your issue.

Best,
Nithesh
Hajie CarpioHajie Carpio
I think this will also work.

JSONParser parser = JSON.createParser(response.getBody());
<Class/Object> ResponseObject = (<Class/Object>) parser.readValueAs(<Class/Object>.class);
Ankita Rustagi 11Ankita Rustagi 11
Thanks Nitesh. Nice Explaination.