[SalesForce] How to Deserialze JSON Object and save them to salesforce

I have the following JSON reponse format. I would like to save only specific information on salesforce i.e. all the user details, description, zip code, location, request_status, space and state:

{
"response":{
    "request_id":527136,
    "request_type_id":30822,
    "request_type_foreign_id":"",
    "request_type_cost":0,
    "request_type_name":"Street Lighting",
    "department_id":2336,
    "department_name":"Customer Service Centre",
    "gov_user":"Sandy Burke",
    "foreign_id":null,
    "display_foreign_id":false,
    "device":"web",
    "user":"",
    "user_detail":{"firstname":"Tony","lastname":"Andrew","email":"email@email.com","phone":"","address":null,"zipcode":null,"space":null,"state":null},
    "request_status":"submitted",
    "date_created":1415979365,
        "date_due":0,
        "count_followers":0,
        "count_comments":0,
        "count_supporters":0,
        "count_flagged":0,
        "title":"Street Lighting",
        "description":"TEST API test",
        "is_visible":false,
        "address":"",
        "zipcode":"PE1 1EJ",
        "location":"Peterborough, England",
        "space":"Peterborough",
        "state":"England",
        "priority":"medium",
        "category":null,
        "lat":52.234531,
        "lon":0.128064,
        "image_thumbnail":"",
        "image":"",
        "request_url":"https:\/\/www.publicstuff.com\/england\/peterborough-uk\/street-lighting\/street-lighting-527136",
        "url_title":"Publicstuff ~ Street Lighting ~ Street Lighting in Peterborough",
        "custom_fields":[
        {
            "custom_field":{
                "id":543594,
                "foreign_id":null,
                "name":"What type of fault is it?","description":"",
                "type":"singleselect",
                "value":"Light out",
                "is_public":1,
                "option_id":247950,
                "option_description":"",
                "option_foreign_id":null,
                "order":4
                }
                },
                {
                    "custom_field":{
                        "id":543593,
                        "foreign_id":null,
                        "name":"What is the number displayed on the light column?",
                        "description":"Each street light has a unique number and we ask that you provide this in the above box.  The number format is 'PCC' followed by numbers for example, PCC12.  ",
                        "type":"text",
                        "value":"TEST123",
                        "is_public":1,
                        "option_id":null,
                        "option_description":null,
                        "option_foreign_id":null,
                        "order":2
                        }
                        }
                        ],
                        "status":{
                            "type":"success",
                            "message":"Success",
                            "code":200,
                            "code_message":"Ok"
                        }
        }
}

I have tried the following: Creates wrapper classes:

public class DeserializedJSONresponse{

public class UserDetails
{
    public final Integer request_id;
    public final Integer request_type_id;
    public final String request_type_foreign_id;
    public final Integer request_type_cost;
    public final String request_type_name;
    public final Integer department_id;
    public final String department_name;
    public final String gov_user;
    public final Integer foreign_id;
    public final Boolean display_foreign_id;
    public final String device;
    public final String user;

    //Type
    public final List<User_Details> user_detail;

    public final String request_status;
    public final Integer date_created;
    public final Integer date_due;
    public final Integer count_followers;
    public final Integer count_comments;
    public final Integer count_supporters;
    public final Integer count_flagged;
    public final String title;
    public final String description;
    public final Boolean is_visible;
    public final String address;
    public final String zipcode;
    public final String location;
    public final String space;
    public final String state;
    public final String priority;
    public final String category;
    public final Integer lat;
    public final Integer lon;
    public final Blob image_thumbnail;
    public final Blob image;
    public final String request_url;
    public final String url_title;
    public final List<CustomFields> custom_fields;
    public final List<statuses> status;
} .. other wrapper classes follows

and also a function to set up Http and Deserialize the JSON object:

public String postRequestCall(){
    JSONGenerator gen = JSON.createGenerator(true);

    HttpRequest req = new HttpRequest();
    req.setMethod('GET');
    req.setEndpoint('https://www.publicstuff.com/api/2.0/request_view?request_id=527136');
    req.setHeader('PublicStuff-Key', '5srT1Fdaeal25f23***********');
    Http http = new Http();
    HTTPResponse res = http.send(req);        

    String resonseBody = res.getBody();
    JSONParser parser = JSON.createParser(res.getBody());

    DeserializedJSONresponse reqs = new DeserializedJSONresponse();
    DeserializedJSONresponse.UserDetails URequest= (DeserializedJSONresponse.UserDetails)System.JSON.deserialize(resonseBody, DeserializedJSONresponse.UserDetails.class);
    System.debug('PublicStuffTrialClass UserRequest ' + URequest);

    return res.getBody();
}

Best Answer

I prefer using the JSON.deserializeUntyped() to get specific values.

//use the Map<String,Object> to get the values of the JSON
String jsonString = 'YOUR JSON BODY';
Map<String,Object> rawObj = (Map<String,Object>) JSON.deserializeUntyped(jsonString);
//the response fields are stored as an object in the "response": field. So you have to get that field before getting it's child fields.
Map<String,Object> responseObj = (Map<String,Object>)rawObj.get('response');
//this will get child objects
Map<String,Object> userDetails = (Map<String,Object>) responseObj.get('user_detail');
//loop through details
for (String field : userDetails.keySet()){
    system.debug('The field: ' + field);
    Object o = userDetails.get(ks);
    system.debug('The value: ' + o);
    //if you want to reference an sObject field you could do
    MySObjectRec.put(ks,o);
}
//select a specific value
String requestStatus = (String) responseObj.get('request_status');
String firstName = (String) userDetails.get('firstname');

You could also use a List<Object> listObj = responseObj.get('arrayVar'); if the value is an array and then loop through that.

Related Topic