[SalesForce] APEX Deserializing/Parsing RESTful JSON Webservice Response

I'm trying to get JSON data from a RESTful webservice into SFDC.

My attempts have failed as I keep getting the following error:

System.JSONException: Malformed JSON: Expected '{' at the beginning of
object

Here my code:

JSON Response snippet

[
{
    "territoryId": "999991",
    "territoryName": "999991-Test",
    "startDate": "2018-01-01T00:00:00Z",
    "endDate": "9999-12-31T00:00:00Z",
    "recordIndex": 1
},
{
    "territoryId": "139445",
    "territoryName": "ABILENE TX DIAB PC1 139445",
    "startDate": "2016-07-01T00:00:00Z",
    "endDate": "9999-12-31T00:00:00Z",
    "recordIndex": 2
},]

Wrapper Class

public class HAPI_TerrByCount_wrapper {

public class TerritoriesByCountry {

    public String territoryId {get; set;}
    public String territoryName {get; set;}
    public String startDate {get; set;}
    public String endDate {get; set;}
    public Integer recordIndex {get; set;}
}

public List<TerritoriesByCountry> terrByCountList {get; set;}}

Callout Class

public class HAPI_callOut {

public HAPI_TerrByCount_wrapper wrapper {get; set;}

public void deserialize() {

    HttpRequest request = new HttpRequest();

    request.setEndpoint('callout:HAPI_CallOut/territories-by-country/US');
    request.setMethod('GET');
    request.setTimeout(120000);

    Http service = new Http();
    HttpResponse response = service.send(request);

    wrapper = (HAPI_TerrByCount_wrapper) System.JSON.deserialize(response.getBody(), HAPI_TerrByCount_wrapper.class);
}}

I understand that the JSON response is an Array and the deserializer is expecting a string, but digging through this website I still was not able to fix it.

Best Answer

You need to deserialize into a List.

List<HAPI_TerrByCount_wrapper> wrappers = (List<HAPI_TerrByCount_wrapper>)JSON.deserialize(
    response.getBody(), List<HAPI_TerrByCount_wrapper>.class
);
Related Topic