ApiResponse class with an Id as a Json key

Synops :

I am trying to consume data from some public API but I am stuck on some issue about the design of this data. I am using Spring.

I am doing it with the classic way :

private ResponseEntity<ApiResponse> getVehicules() {
    final String methodUri = "/vehicules";
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    return restTemplate.exchange(apiUri + methodUri, HttpMethod.GET, entity, ApiResponse.class);
}

The problem is more about the design of ApiResponse class. Indeed, the api returned json looks like :

{
    "status": "ok",
    "meta": {
        "count": 2,
        "page_total": 1,
        "limit": 100,
        "page": null
    },
    "data": {
        "18497": {
            "id": 18497,
            "name": "vehiculeName",
            "nation": "vehiculeNation"
        },
        "52467": {
            "id": 52467,
            "name": "anotherVehiculeName",
            "nation": "anotherVehiculeNation"
        }
    }
}

So how do I manage the id (The one before the brackets - ex 18497:{...} ) in my class ?

I am stuck trying to create a Data class because of that and as you can imagine, its a public API not mine, so I can't change anything on this side.

Dherik :

This kind of weird Json (using dynamic information in field names) is tricky to figure out how to read. But the solution is simple.

You will need to use a Map on your ApiResponse class, like:

class ApiResponse {

    // other fields

    @JsonProperty("data")
    private Map<String, VehicleResponse> vehicles;

}

The VehicleResponse is a normal class with id, name, nation fields.

As result, the map vehicles will have as key the 18497 (and etc) and as value the information about the vehicle (id, name, nation) in VehicleResponse.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=358195&siteId=1