[SalesForce] How to handle REST API JSON response

Is there a good practise,
to get the Ip out of the rest JSON response:

{
    "id" : "001D000000IqhSLIAZ",
    "errors" : [ ],
    "success" : true
}

What I do:

HttpResponse res = h.send(req);
if(res.getStatusCode()==201) {
    JSONParser parser = JSON.createParser(res.getBody());
    parser.nextToken();
    parser.nextValue();
    return parser.getIdValue();
} else {
    return null;
}

What I like to do is something like:

HttpResponse res = h.send(req);
if(res.getStatusCode()==201) {
    customObject__c customObject = (customObject__c) JSON.deserialize(res.getBody(),customObject__c.class);
    return customObject.Id;
} else {
    return null;
}

logically leads me to:

No such column 'success' on sobject of type customObject__c

Best Answer

Take alook at the JSON2Apex app (credits to @metadaddy and & @superfell)

You basically paste in your json, the tool generates a apex class which you can use to easily parse your json, and access data from attributes instead of parsing the json manually.

This would be the result for your json.

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class JSON2Apex {

    public String id;
    public List<Errors> errors;
    public Boolean success;

    public class Errors {
    }


    public static JSON2Apex parse(String json) {
        return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
    }

    static testMethod void testParse() {
        String json = '{'+
        '    \"id\" : \"001D000000IqhSLIAZ\",'+
        '    \"errors\" : [ ],'+
        '    \"success\" : true'+
        '}';
        JSON2Apex obj = parse(json);
        System.assert(obj != null);
    }
}
Related Topic