RestTemplate getForEntity map for a list of objects

I have a response from a URL that looks like this:

{"seq":1,"id":"Test1","changes":[{"rev":"1-52f5cdf008ecfbadf621c2939af7bd80"}]} {"seq":2,"id":"Test2","changes":[{"rev":"1-8ce403a89dc5e7cb4187a16941b3fb7d"}]} {"seq":3,"id":"Test3","changes":[{"rev":"1-52as7ddfd8ecfbadf621c2939af7bd80"}]} {"seq":4,"id":"Test4","changes":[{"rev":"1-6yy03a89dc5e7cb45677a16941b3fb7d"}]} 

If the display object is String, then it receives all change feeds.

 ResponseEntity<String> responseEntity = restTemplate.exchange(URL, HttpMethod.GET, requestEntity, String.class); 

Whereas if I use a custom Value object, for example:

 public class KnChanges { private long seq; private String id; private List changes; 

with getter and setter methods, then I get only the first data about the document change. Even if KnChanges [] (array) is used, only the first change is obtained.

Could you please help how the JSON list structure mentioned above can be mapped to an object?

Thanks Harsha

+6
source share
2 answers
 ParameterizedTypeReference<List<KnChanges>> responseType = new ParameterizedTypeReference<List<KnChanges>>() {}; ResponseEntity<List<KnChanges>> resp = restTemplate.exchange(URL, HttpMethod.GET, requestEntity, responseType); List<KnChanges> list = resp.getBody(); 
+4
source

Some people asked for a better answer with some explanation. So here it is:

As sujim said : you need

 ParameterizedTypeReference<List<KnChanges>> responseType = new ParameterizedTypeReference<List<KnChanges>>() {}; ResponseEntity<List<KnChanges>> resp = restTemplate.exchange(URL, HttpMethod.GET, requestEntity, responseType); List<KnChanges> list = resp.getBody(); 

Explaination:

The last parameter to invoke the exchange method defines the class that is created when the response is received. Then the response data will be mapped to the resulting object. So you need List.class in the first place. Because you are expecting a JSON array. Now you need to determine the content type of this List . Here erasing like Java throws stones on your way. Because Java removes generic type information at compile time, you cannot just define the expected List as List<KnChanges>.class . β€œFortunately” is a hack;) And this hack is new ParameterizedTypeReference<List<KnChanges>>() {} . Provided that the application can read general type information at runtime. And therefore, it is able to match the received data with your Java objects.

As a side note: There are several implementations of this hack. It is commonly used for dependency injection systems or mapping systems where type erasure can sometimes occur. Googles Guava also offers an implementation. See code for more information. There you can also learn how to do it if you want.

+1
source

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


All Articles