How To Use Json. Deserialize Apex In A Proper Manner?

372    Asked by Unnatigautam in Salesforce , Asked on Sep 22, 2023

Can you tell me how to deserialize the below-mentioned JSON object?

{
    "response": {
        "count": 1,
        "benchmark": 0.22567009925842,
        "requests": [
            {
                "request": {
                    "id": 537481,
                    "image_thumbnail": "",
                    "title": "Request for new bin(s) - residential",
                    "description": "Propmain ref  3234-1114",
                    "status": "submitted",
                    "address": "36 Pine Tree Close",
                    "location": "Peterborough, England",
                    "zipcode": "PE1 1EJ",
                    "user": "",
                    "date_created": 1417173208,
                    "count_comments": 0,
                    "count_followers": 0,
                    "count_supporters": 0,
                    "lat": 52.599967,
                    "lon": -0.233482,
                    "user_follows": 0,
                    "user_comments": 0,
                    "user_request": 1,
                    "rank": "0"
                }
            }
        ],
        "status": {
            "type": "success",
            "message": "Success",
            "code": 200,
            "code_message": "Ok"
        }
    }
}
What i've tried:
 Map rawObj = (Map) JSON.deserializeUntyped(jsonString);
    Map responseObj = (Map)rawObj.get('response');
    List<Object> reqs = (List<Object>) responseObj.get('requests');
    System.debug('Map Size = ' + reqs.size());
    Map i = new Map ();
    for (Object x : reqs) {
         i = (Map)x;
}
    Map requests = (Map)i.get('request');
    System.debug('Map Size = ' + i.size());
    for (String field : i.keySet()){
        Object id = i.get(field);
        Object title = i.get('title');
        System.debug('Id : ' + id);
        System.debug('title : ' + title);
        //System.debug('Title : ' + title);
      }


Answered by Unnati gautam

What you can do is paste the JSON into http://json2apex.herokuapp.com/ and then attempt the generated code. This particular tool produces normal Apex class es containing a field per JSON field. After that, you can parse with one JSON.deserialize.apex call. The code mentioned below has been produced from your JSON. It is also possible to rename the classes and modify the data types. You can use Decimal in place of Double in case you are working with money.

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//
public class JSON2Apex {
    public class Status {
        public String type;
        public String message;
        public Integer code;
        public String code_message;
    }
    public class Requests {
        public Request request;
    }
    public Response response;
    public class Response {
        public Integer count;
        public Double benchmark;
        public List requests;
        public Status status;
    }
    public class Request {
        public Integer id;
        public String image_thumbnail;
        public String title;
        public String description;
        public String status;
        public String address;
        public String location;
        public String zipcode;
        public String user;
        public Integer date_created;
        public Integer count_comments;
        public Integer count_followers;
        public Integer count_supporters;
        public Double lat;
        public Double lon;
        public Integer user_follows;
        public Integer user_comments;
        public Integer user_request;
        public String rank;
    }
    public static JSON2Apex parse(String json) {
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
    }
    static testMethod void testParse() {
        String json = '{'+
        '"response": {'+
        ' "count": 1,'+
        ' "benchmark": 0.22567009925842,'+
        ' "requests": ['+
        ' {'+
        ' "request": {'+
        ' "id": 537481,'+
        ' "image_thumbnail": "",'+
        ' "title": "Request for new bin(s) - residential",'+
        ' "description": "Propmain ref 3234-1114",'+
        ' "status": "submitted",'+
        ' "address": "36 Pine Tree Close",'+
        ' "location": "Peterborough, England",'+
        ' "zipcode": "PE1 1EJ",'+
        ' "user": "",'+
        ' "date_created": 1417173208,'+
        ' "count_comments": 0,'+
        ' "count_followers": 0,'+
        ' "count_supporters": 0,'+
        ' "lat": 52.599967,'+
        ' "lon": -0.233482,'+
        ' "user_follows": 0,'+
        ' "user_comments": 0,'+
        ' "user_request": 1,'+
        ' "rank": "0"'+
        ' }'+
        ' }'+
        ' ],'+
        ' "status": {'+
        ' "type": "success",'+
        ' "message": "Success",'+
        ' "code": 200,'+
        ' "code_message": "Ok"'+
        ' }'+
        '}'+
        '}';
        JSON2Apex obj = parse(json);
        System.assert(obj != null);
    }
}

JSON.deserializeUntyped () method can also be used. In case the JSON string is unknown at compile time, or if the JSON string has fields that are not identical to the fields in the Apex class, then the JSON.deserializedUntyped() method can be deployed. This particular method returns a map of the JSON data, where the keys refer to the field names and the values are the respective values.

The JSON.serialize() method can also be used to change an Ap3ex object into a JSON string. This technique consumes an object in the form of an argument and returns a JSON string indication of that specific object.

Apart from the above-mentioned methods, the APEX JSON Parser method can also be used. Apex offers a JSONParser class that can be utilized to parse JSON data. The class offers methods such as getCurrentValue() and nextToken() that can be utilized to scroll through the JSON data. This method proves beneficial when there is a requirement to manage intricate JSON data, which cannot be easily deserialized through the built-in Apex methods.

You can also deploy third-party libraries. There are several third-party libraries present that can be utilized to parse JSON data in APex. A few well-known options comprise JSON2Apex, JSON.org, and JSON.simple. The libraries offer extra functionality and can also prove helpful if the built-in Apex processes do not suffice your requirements. JSON2Apex refers to a third-party library that can be utilized to parse JSON data available in Apex. This library is beneficial when the built-in Apex techniques don’t cater to your demands. It may be utilized to produce Apex classes to deserialize JSON strings into Apex objects.



Your Answer

Interviews

Parent Categories