How to handle a list of resources with ResponseEntity

714 Views Asked by At

I have an external REST API that returns a list of client objects as json. For example:

GET externalapi.io/api/clients

[ {
    "id" : "b15asgdc-6efd-4a2d-re08-2q3r3bae",
    "clientName" : "test1",
    ...
  },
  {
    "id" : "ryec-6efd-4a2d-aa08-29a9drjrteae",
    "clientName" : "test2",
    ...
  },
  ...
]

My API calls this external service using Spring's RestTemplate. The goal is to get the response and parse it into client Java objects. I've tried the following:

HttpEntity<Object> entity = new HttpEntity<Object>(null, headers);

ResponseEntity<String> responseEntityJson = resttemplate.exchange(path, HttpMethod.GET, entity, String.class);

Type listType = new TypeToken<ArrayList<ClientResource>>(){}.getType();

ArrayList<ClientResource> responseResources = gson.fromJson(responseEntityJson.getBody(), listType);

My trouble is with this line:

ResponseEntity<String> responseEntityJson = resttemplate.exchange(path, HttpMethod.GET, entity, String.class);

My hope was that I could get the body as a JSON string, and use Google's GSON to parse it into objects, but this does not seem to work. I've seen suggestions to use

ResponseEntity<ClientResource> responseEntityJson = resttemplate.exchange(path, HttpMethod.GET, entity, ClientResource.class);

but, I don't think this works for a list of resources. I can set ResponseEntity<List<ClientResource>> but .exchange() doesn't easily accept a type like that. How can I handle a list of resources with ResponseEntity?

2

There are 2 best solutions below

1
On BEST ANSWER

Try this please, maybe it works for you.

HttpHeaders headers = new HttpHeaders();
// set headers if required

HttpEntity<?> entity = new HttpEntity<>(headers);

String url = "https://externalapi.io/api/clients";

ParameterizedTypeReference<List<ClientResource>> responseType = new ParameterizedTypeReference<List<ClientResource>>() {};
ResponseEntity<List<ClientResource>> response = restTemplate.exchange(url, HttpMethod.GET, entity, responseType);

List<ClientResource> clientResources = response.getBody();
0
On

Madan's code should work. Next to using the Gson library from Google you can also use ObjectMapper from the Jackson library.

See the following:

HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity<Object> entity = new HttpEntity<Object>(null, headers);

ResponseEntity<String> response = resttemplate.exchange(
"https://externalapi.io/api/clients", HttpMethod.GET, entity, String.class);

ObjectMapper objectMapper = new ObjectMapper();
List<ClientResource> clients = objectMapper.readValue(
response.getBody(), new TypeReference<List<ClientResource>>() {});