【发布时间】:2016-05-31 18:26:21
【问题描述】:
当使用RestTemplate.exchange 调用查询端点时,我应该期待什么返回类型?
我的存储库有一个方法:
Page<Account> findAccountByFirstName(String name, Pageable pageable);
在我的集成测试中,我使用RestTemplate 进行以下调用:
ResponseEntity<List<Account>> accountResponse = restPleb.exchange(
new RequestEntity<Void>(HttpMethod.GET, getUri("/accounts/search/findByFirstName?firstName=Kevin")),
new ParameterizedTypeReference<List<Account>>() {}
);
响应包含在名为 accounts 的对象中找到的资源列表:
{
"_embedded" : {
"accounts" : [ {
"lastName" : "Lastname",
"firstName" : "Kevin",
"phoneNumber " : "+44 7700000000",
"email" : "kevin@example.com",
"_links" : {
"self" : {
"href" : "http://localhost:53826/accounts/id"
},
"persistableAccount" : {
"href" : "http://localhost:53826/accounts/id"
}
}
} ]
},
"_links" : {
"self" : {
"href" : "http://localhost:53826/accounts/search/findByFirstName?firstName=Kevin"
}
},
"page" : {
"size" : 20,
"totalElements" : 1,
"totalPages" : 1,
"number" : 0
}
}
我在RestTemplate 和杰克逊之间收到以下错误,无法弄清楚如何处理响应。大概这是因为它需要一个数组而不是一个对象。
org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
有没有办法让RestTemplate 向杰克逊提供正确的提示以正确反序列化?我本以为一定有办法,就是分水岭两边都是春天!
更新
我尝试将响应类型指定为Resources<Account>,这样可以防止抛出异常,而是给出一个空列表:Resources { content: [], links: [] }
【问题讨论】:
-
你在检查 accountResponse.getBody() 吗?给你帐户列表?
-
@VinayVeluri 在
exchange调用完成之前抛出异常,因此accountResponse永远不会被分配。
标签: java jackson spring-data spring-data-rest resttemplate