Skip to content
Advertisement

RestTemplate get list from specific json structure

The json is of this structure:

{
"data": [{"id":"1", "name":"foo"}]
}

I have a DTO of the form

class Domain {
  String id;
  String domain;
}

I want to parse the array into List and ignore data. This is the code:

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

But I get this exception

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]

Advertisement

Answer

I would suggest you changing your model as follows:

class ResponseDomainData {
  List<Domain> data;
}

class Domain {
  String id;
  String name;
}

And your test also:

@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);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement