我有两个问题:
如何使用Spring RestTemplate映射JSON对象列表。 如何映射嵌套的JSON对象。
我试图消费https://bitpay.com/api/rates,从http://spring.io/guides/gs/consuming-rest/遵循教程。
我有两个问题:
如何使用Spring RestTemplate映射JSON对象列表。 如何映射嵌套的JSON对象。
我试图消费https://bitpay.com/api/rates,从http://spring.io/guides/gs/consuming-rest/遵循教程。
当前回答
作为一个通用模块,Page<?>对象可以被模块反序列化,就像JodaModule, Log4jJsonModule等。参考我的回答。使用Pageable字段测试端点时出现JsonMappingException
其他回答
作为一个通用模块,Page<?>对象可以被模块反序列化,就像JodaModule, Log4jJsonModule等。参考我的回答。使用Pageable字段测试端点时出现JsonMappingException
考虑一下这个答案,特别是如果你想在列表中使用泛型 Spring RestTemplate和泛型类型ParameterizedTypeReference集合,如List<T>
首先定义一个对象来保存返回数组的实体。如。
@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[]。
在我的情况下,我更喜欢提取一个字符串,然后使用JsonNode接口浏览上下文
var response = restTemplate.exchange("https://my-url", HttpMethod.GET, entity, String.class);
if (response.getStatusCode() == HttpStatus.OK) {
var jsonString = response.getBody();
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree(jsonString);
System.out.println(actualObj);
}
或者很快
ObjectNode actualObj= restTemplate.getForObject("https://my-url", ObjectNode.class);
然后读取内部数据与路径表达式,即。
boolean b = actualObj.at("/0/states/0/no_data").asBoolean();
你可以为每个条目创建POJO,
class BitPay{
private String code;
private String name;
private double rate;
}
然后使用BitPay列表的ParameterizedTypeReference,你可以使用:
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<List<Employee>> response = restTemplate.exchange(
"https://bitpay.com/api/rates",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<BitPay>>(){});
List<Employee> employees = response.getBody();