[SalesForce] Way to parse JSON object with dynamic number of fields

Below is the sample JSON string I received from our web service:

{
    "id": 1,
    "result": {
        "0": 15,
        "1": 16
    },
    "error": null
}

Please notice that in the result section, the number of returned parameters can be increased. And we no idea how many will the greatest number be before execution. And it is not an array. Is there any way we can parse this JSON string into an Apex object?

No is an acceptable answer but it would require us to update the API.

Best Answer

Create a separate wrapper class

Class ResponseWrap {
    public Integer id;
    public Map<String, Integer> result; //Use proper data types according to your requirement these are samples provided
    public String error;
}

Call this method where you want to handle the response

public ResponseWrap class webserviceResponseHandler(String responseJSON) {
    try {
        ResponseWrap response = (ResponseWrap)JSON.deserialize(responseJSON, ResponseWrap.class);
    } catch(Exception ex) {
        //handle exception
    }

    return response;
}

Method webserviceResponseHandler() will return you the JSON parser result.

Related Topic