Return the list <myObj> returned by ResponseEntity <List>

My REST client uses RestTemplate to get a list of objects.

ResponseEntitiy<List> res = restTemplate.postForEntity(getUrl(), myDTO, List.class); 

Now I want to use the returned list and return it as a List in the calling class. In the case of a string, you can use toString, but what is the work for lists?

+11
source share
4 answers

First of all, if you know the type of items in your list, you can use the ParameterizedTypeReference class.

 ResponseEntity<List<MyObj>> res = restTemplate.postForEntity(getUrl(), myDTO, new ParameterizedTypeReference<List<MyObj>>() {}); 

Then, if you just want to return a list you can do:

 return res.getBody(); 

And if all you care about is a list, you can simply do:

 // postForEntity returns a ResponseEntity, postForObject returns the body directly. return restTemplate.postForObject(getUrl(), myDTO, new ParameterizedTypeReference<List<MyObj>>() {}); 
+15
source

I could not accept the accepted answer to work. It seems that postForEntity no longer has this method signature. Instead, I had to use restTemplate.exchange() :

 ResponseEntity<List<MyObj>> res = restTemplate.exchange(getUrl(), HttpMethod.POST, myDTO, new ParameterizedTypeReference<List<MyObj>>() {}); 

Then, to return the list as above:

 return res.getBody(); 
+11
source

In the latest version (Spring Framework 5.1.6), both answers do not work. As postForEntity mentioned in its answer postForEntity signature of the postForEntity method postForEntity changed. Also restTemplate.exchange() and its overloads require a RequestEntity<T> object or its parent HttpEntity<T> . Unable to transfer my DTO object as mentioned.

Check out the RestTemplate class documentation

Here is the code that worked for me

 List<Shinobi> shinobis = new ArrayList<>(); shinobis.add(new Shinobi(1, "Naruto", "Uzumaki")); shinobis.add(new Shinobi(2, "Sasuke", "Uchiha"); RequestEntity<List<Shinobi>> request = RequestEntity .post(new URI(getUrl())) .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .body(shinobis); ResponseEntity<List<Shinobi>> response = restTemplate.exchange( getUrl(), HttpMethod.POST, request, new ParameterizedTypeReference<List<Shinobi>>() {} ); List<Shinobi> result = response.getBody(); 

Hope this helps someone.

+1
source

You have deployed ResponseEntity and can get an object (list)

  res.getBody() 
0
source

Source: https://habr.com/ru/post/1200556/


All Articles