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

扶醉桌前 提交于 2019-12-08 13:46:09

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/53494143/resttemplate-map-json-key-value-pair-object-with-with-dynamic-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!