我有两个问题:

如何使用Spring RestTemplate映射JSON对象列表。 如何映射嵌套的JSON对象。

我试图消费https://bitpay.com/api/rates,从http://spring.io/guides/gs/consuming-rest/遵循教程。


当前回答

我在这里遇到的最大问题是构建将RestTemplate匹配到兼容类所需的Object结构。幸运的是,我找到了http://www.jsonschema2pojo.org/(在浏览器中获得JSON响应并将其作为输入),我非常推荐这个功能!

其他回答

我从这个帖子https://jira.spring.io/browse/SPR-8263找到了工作。

基于这篇文章,你可以返回一个类似这样的列表:

ResponseEntity<? extends ArrayList<User>> responseEntity = restTemplate.getForEntity(restEndPointUrl, (Class<? extends ArrayList<User>>)ArrayList.class, userId);

首先定义一个对象来保存返回数组的实体。如。

@JsonIgnoreProperties(ignoreUnknown = true)
public class Rate {
    private String name;
    private String code;
    private Double rate;
    // add getters and setters
}

然后你可以使用该服务并通过以下方式获得一个强类型列表:

ResponseEntity<List<Rate>> rateResponse =
        restTemplate.exchange("https://bitpay.com/api/rates",
                    HttpMethod.GET, null, new ParameterizedTypeReference<List<Rate>>() {
            });
List<Rate> rates = rateResponse.getBody();

上面的其他解决方案也可以工作,但我喜欢得到一个强类型列表,而不是Object[]。

作为一个通用模块,Page<?>对象可以被模块反序列化,就像JodaModule, Log4jJsonModule等。参考我的回答。使用Pageable字段测试端点时出现JsonMappingException

我在这里遇到的最大问题是构建将RestTemplate匹配到兼容类所需的Object结构。幸运的是,我找到了http://www.jsonschema2pojo.org/(在浏览器中获得JSON响应并将其作为输入),我非常推荐这个功能!

对我来说这很有效

Object[] forNow = template.getForObject("URL", Object[].class);
    searchList= Arrays.asList(forNow);

Object是你想要的类的位置