首页 > 解决方案 > 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]

标签: javaspringjacksonresttemplate

解决方案


我建议你改变你的模型如下:

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);
}

推荐阅读