Spring RestTemplate发送列表获取列表 [英] Spring RestTemplate Send List an get List

查看:2884
本文介绍了Spring RestTemplate发送列表获取列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Spring的 RestTemplate 进行服务,在我的服务方面,代码是这样的:

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);

我无法使用 p 对象如列表< Person> ,它将变为 LinkedHashList
经过一番研究后,我找到了一个解决方案,说我必须用交换方法调用服务:

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?

推荐答案

检查您的代码是否如下所示。这应该有效。

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>>() {});

这篇关于Spring RestTemplate发送列表获取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆