Java SpringREST模板Json输出映射到对象
当我使用SpringREST模板进行API调用时,得到如下所示的Json响应Java SpringREST模板Json输出映射到对象,java,json,spring,spring-mvc,resttemplate,Java,Json,Spring,Spring Mvc,Resttemplate,当我使用SpringREST模板进行API调用时,得到如下所示的Json响应 [ { "Employee Name": "xyz123", "Employee Id": "12345" } ] 我创建对象来映射json响应,如下所示: public class Test { @JsonProperty("Employee Name")
[
{
"Employee Name": "xyz123",
"Employee Id": "12345"
}
]
我创建对象来映射json响应,如下所示:
public class Test {
@JsonProperty("Employee Name")
private String employeeName;
@JsonProperty("Employee Id")
private String employeeId;
}
但我在调用rest api时遇到以下错误:
JSON解析错误:无法反序列化启动数组令牌之外的com.pojo.Emp
实例;嵌套异常为com.fasterxml.jackson.databind.exc.MismatchedInputException:
无法在[Source:(PushbackInputStream);行:1,列:1处反序列化起始\u数组令牌之外的com.pojo.Emp
实例
当Json在参数键中有空格时,如何将Rest模板Json响应映射到对象?看起来您正在尝试将数组映射到对象。您可以执行以下操作
ResponseEntity<Test[]> response =
restTemplate.getForEntity(
url,
Test[].class);
Test[] employees = response.getBody();
ResponseEntity响应=
restTemplate.getForEntity(
网址,
测试[]类);
Test[]employees=response.getBody();
有关更多信息,请检查您的JSON响应是一个对象数组,因为它被包装在
[]
中,所以请将数据映射到列表中。此处使用参数化TypeReference
创建列表的TypeReference
ResponseEntity response=restemplate.exchange(endpointUrl,
HttpMethod.GET,httpEntity,
新的ParameteredTypeReference(){});
List employees=response.getBody();
您可以演示如何使用rest模板调用rest API吗?ResponseEntity resp=restTemplate.exchange(endpointUrl、HttpMethod.GET、httpEntity、EmpApp.class);谢谢Pankaj,您的回答帮助我理解使用rest模板处理列表对象的方法
ResponseEntity<List<Emp>> response = restTemplate.exchange(endpointUrl,
HttpMethod.GET,httpEntity,
new ParameterizedTypeReference<List<Emp>>(){});
List<Emp> employees = response.getBody();