java - RestTemplate 从特定的 json 结构中获取列表
问题描述
json是这样的结构:
{
"data": [{"id":"1", "name":"foo"}]
}
我有一个表格的 DTO
class Domain {
String id;
String domain;
}
我想将数组解析为 List 并忽略数据。这是代码:
@WithUserDetails("testuser")
@Test
public void test_get_domains_api() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.add("User-Agent", "Spring's RestTemplate" );
headers.add("Authorization", "Bearer "+TOKEN );
ResponseEntity<Map<String, List<Domain>>> response = restTemplate.exchange(
"https://sample/v1/sites",
HttpMethod.GET,
new HttpEntity<>("parameters", headers),
Map<String, List<Domain>>.class
);
System.out.println(response.getBody());
assertNotNull(response);
}
但我得到了这个例外
Error while extracting response for type [class [Lcom.commengine.entity.Domain;]
and content type [application/json];
nested exception is org.springframework.http.converter.HttpMessageNotReadableException:
JSON parse error:
Cannot deserialize instance of [Lcom.commengine.entity.Domain; out of START_OBJECT
token; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize
instance of [Lcom.commengine.entity.Domain; out of START_OBJECT token
at [Source: (PushbackInputStream); line: 1, column: 1]
解决方案
我建议你改变你的模型如下:
class ResponseDomainData {
List<Domain> data;
}
class Domain {
String id;
String name;
}
你的测试也是:
@WithUserDetails("testuser")
@Test
public void test_get_domains_api() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
headers.add("User-Agent", "Spring's RestTemplate" );
headers.add("Authorization", "Bearer "+TOKEN );
ResponseEntity<ResponseDomainData> response = restTemplate.exchange(
"https://sample/v1/sites",
HttpMethod.GET,
new HttpEntity<>("parameters", headers),
ResponseDomainData.class
);
System.out.println(response.getBody());
assertNotNull(response);
}
推荐阅读
- wpf - 在 PowerShell 中将 WPF XAML 链接到 DataGrid
- sql - array_agg() 或 string_agg() 在 redshift 上的替代品
- java - 使用 JPA 实体填充 MySQL 数据库的性能非常慢
- sonarqube - 如何在 sonarQube 中集成 SVN 进行分析
- c# - 事件没有按顺序发生
- curl - 下载 nexus 工件(来自原始存储库)
- common-lisp - 读取合格符号
- xcode - Swift:最小的可执行 for 循环
- jquery - 导出 jQuery DataTable 时自定义数据
- xml - 如何在 PowerShell 中更改 xml 对象的版本属性?