Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to make a service with Spring's RestTemplate, in my service side the code is like this :

@PostMapping(path="/savePersonList")
@ResponseBody
public List<Person> generatePersonList(@RequestBody List<Person> person){
    return iPersonRestService.generatePersonList(person);
}

In client side if I call the service with this code:

List<Person> p = (List<Person>) restTemplate.postForObject(url, PersonList, List.class);

I can't use the p object as List<Person>, it will become a LinkedHashList. After some research I find a solution that said I have to call the service with exchange method:

ResponseEntity<List<Person>> rateResponse = restTemplate.exchange(url, HttpMethod.POST, personListResult, new ParameterizedTypeReference<List<Person>>() {});

and with this solution the server can't take the object and raise an exception , what's the correct way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
245 views
Welcome To Ask or Share your Answers For Others

1 Answer

Check if your code is like below. 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, HttpMethod.POST, requestEntity,new ParameterizedTypeReference<List<Person>>() {});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...