简体   繁体   中英

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, ???);

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);
    }
}

您可以将ParameterizedTypeReferenceMap一起使用(您可以根据自己的用例进行自定义):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM