Spring RestTemplate在尝试反序列化嵌套的对象列表时返回null对象
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring RestTemplate在尝试反序列化嵌套的对象列表时返回null对象相关的知识,希望对你有一定的参考价值。
所以这是我试图转换为Java bean的Json
我使用jackson将JSON绑定到我的数据对象
{
"legend": {
"id": "379ec5d8c",
"name": "Stabil Koos",
"payers": [{
"id": "ab1651df-b835-495558-a2a5-2e6d42f7a41e",
"ranking": 1,
"buyer": {
"id": "67a6359838-0fda-43a6-9e2b-51a7d399b6a1",
"nationality": "en",
"stats": {
"gameeCount": 16581,
"count": 99098
}
}
},
{
"id": "379ecw555d8c",
"ranking": 2,
"buyer": {
"id": "2b451d0eda-ab0c-4345660-be3f-6ba3bebf1f81",
"nationality": "no",
"stats": {
"gamerCount": 1182,
"count": 7113
}
}
}
]
}
}
我的豆子看起来像这样;
public class League implements Serializable {
private String id;
private String name;
@JsonUnwrapped
private List<Payer> payers;
// getters and setters
付款人豆:
public class Payers implements Serializable {
private String id;
private long ranking;
private Buyer buyer;
// getters and setters
我在Junit中使用Rest Template和postForObject
@Before
public void beforeTest() {
restTemplate = new RestTemplate();
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
entity = new HttpEntity(REQUEST, headers);
}
我检索对象的最终代码是:
@Test
public void retrieveData() {
League league = restTemplate.postForObject(ENDPOINT_URL, entity, League.class);
System.out.println(legend);
}
答案
您显示的JSON是针对具有league
属性的对象,该属性是League
对象而不是联盟对象本身。您还需要一个额外的响应类:
class LeagueResponse {
private League league;
League getLeague() { return league; }
}
和:
LeagueResponse leagueResponse = restTemplate.postForObject(ENDPOINT_URL, entity, LeagueResponse.class);
League league = leagueResponse.getLeague();
以上是关于Spring RestTemplate在尝试反序列化嵌套的对象列表时返回null对象的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot:没有从字符串值反序列化的字符串参数构造函数/工厂方法
Spring 尝试反序列化为 LinkedHashMap 而不是 POJO