RestTemplate 从特定 json 结构中获取列表

RestTemplate get list from specific json structure

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