RestTemplate映射带有动态键的JSON键-值对对象

时间:2018-11-27 06:46:50

标签: java spring-boot resttemplate objectmapper

对于使用Java Spring RestTemplate完成的HTTP请求,我获得了带有动态键的JSON键-值对对象的响应,如下所示。

回复:

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

如何将响应对象映射到POJO或Map?

我正在按以下方式使用RestTemplate。

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

2 个答案:

答案 0 :(得分:1)

您可以使用new ObjectMapper.readValue()并将TypeReference指定为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);
    }
}

答案 1 :(得分:1)

您可以简单地将 ParameterizedTypeReference 地图结合使用(可以根据使用情况对其进行自定义):

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