0

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, ???);
Shanika Ediriweera
  • 1,975
  • 2
  • 24
  • 31

2 Answers2

4

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>>() {});
Emre Savcı
  • 3,034
  • 2
  • 16
  • 25
1

You could use the new ObjectMapper.readValue() and specify TypeReference as new TypeReference<Map<String, SimplePOJO>>() {});

public static void main(String[] args) throws IOException {
    final String json = "{\"1234x\": {\"id\": \"1234x\", \"description\": \"bla bla\"}, \"5678a\": {\"id\": \"5678a\", \"description\": \"bla bla bla\"}}";
    Map<String, SimplePOJO> deserialize =
            new ObjectMapper().readValue(json, new TypeReference<Map<String, SimplePOJO>>() {});
}

public static class SimplePOJO {
    private String id;
    private String description;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        SimplePOJO that = (SimplePOJO) o;
        return Objects.equals(id, that.id) &&
                Objects.equals(description, that.description);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, description);
    }
}
Mr. Skip
  • 417
  • 4
  • 10
  • How to combine this with `restTemplate.exchange()` method? – Shanika Ediriweera Nov 27 '18 at 07:03
  • 1
    @ShanikaEdiriweera `response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class); Map deserialize = new ObjectMapper().readValue(response.getBody(), new TypeReference>() {});` – Mr. Skip Nov 27 '18 at 07:13