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

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

我收到 JSON 键值对对象的响应,其中包含使用 Java Spring RestTemplate 完成的 HTTP 请求的动态键,如下所示。

响应:

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

您可以使用 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);
    }
}

您可以简单地将 ParameterizedTypeReferenceMap 一起使用(您可以根据您的用例自定义它):

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