Search code examples
javaspring-bootresttemplateobjectmapper

RestTemplate map JSON key-value pair object with with dynamic keys


I get a response of JSON key-value pair object with with dynamic keys for a HTTP request done using Java Spring RestTemplate as shown below.

Response:

{
    "1234x": {
        "id": "1234x",
        "description": "bla bla",
        ... 
    },
    "5678a": {
        "id": "5678a",
        "description": "bla bla bla",
        ... 
    },
    ...
}

How to map the response object to a POJO or a Map ?

I am using RestTemplate as following.

RestTemplate restTemplate = new RestTemplate();
String url = "my url";
HttpHeaders headers = new HttpHeaders();
HttpEntity entity = new HttpEntity(headers);
response = restTemplate.exchange(url, HttpMethod.GET, entity, ???);

Solution

  • You can simply use ParameterizedTypeReference with Map (you can customize it according to your use case) :

    response = restTemplate.exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<Map<String, Object>>() {});