Java – spring resttemplate send list get list
•
Java
I want to use spring's resttemplate to provide services. In terms of my services, the code is as follows:
@PostMapping(path="/savePersonList") @ResponseBody public List<Person> generatePersonList(@RequestBody List<Person> person){ return iPersonRestService.generatePersonList(person); }
On the client side, if I use this code to invoke a service:
List<Person> p = (List<Person>) restTemplate.postForObject(url,PersonList,List.class);
I can't use the P object as list < person >, it will become linkedhashlist After some research, I found a solution that I must call the service with the exchange method:
ResponseEntity<List<Person>> rateResponse = restTemplate.exchange(url,HttpMethod.POST,personListResult,new ParameterizedTypeReference<List<Person>>() {});
And with this solution, the server cannot get the object and throw an exception. Is this the correct method?
Solution
Check that your code is as follows This should work
//header HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); //person list List<Person> personList = new ArrayList<Person>(); Person person = new Person(); person.setName("UserOne"); personList.add(person); //httpEnitity httpentity<Object> requestEntity = new httpentity<Object>(personList,headers); ResponseEntity<List<Person>> rateResponse = restTemplate.exchange(url,requestEntity,new ParameterizedTypeReference<List<Person>>() {});
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码