Synops
Synops

Reputation: 132

ApiResponse class with an Id as a Json key

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.

Upvotes: 1

Views: 161

Answers (2)

Dherik
Dherik

Reputation: 19070

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.

Upvotes: 2

mad_fox
mad_fox

Reputation: 3188

The easiest and fastest way to build java classes from JSON is by using a schema mapper like this one:

http://www.jsonschema2pojo.org/

It generates java classes directly from JSON and also allows you to specify many different options such as the annotation types that should be generated.

Upvotes: 0

Related Questions