英文:
Spring Rest Template Json output mapping to Object
问题
当我使用Spring Rest Template进行API调用时,收到的JSON响应如下所示:
[
{
"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解析错误:无法从START_ARRAY令牌中反序列化
com.pojo.Emp
的实例;嵌套异常是com.fasterxml.jackson.databind.exc.MismatchedInputException:无法从START_ARRAY令牌中反序列化com.pojo.Emp
的实例\n at [Source: (PushbackInputStream); line: 1, column: 1
在JSON参数键中包含空格时,如何将Rest Template的JSON响应映射到对象?
(请注意,以上为您要求的内容的翻译,不包括问题的回答。)
英文:
When i make the API call using Spring Rest template, getting Json response like below
[
{
"Employee Name": "xyz123",
"Employee Id": "12345"
}
]
I was created object to map the json response like below:
public class Test {
@JsonProperty("Employee Name")
private String employeeName;
@JsonProperty("Employee Id")
private String employeeId;
}
But I am getting below error when i make rest api call:
> JSON parse error: Cannot deserialize instance of com.pojo.Emp
out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException:
Cannot deserialize instance of com.pojo.Emp
out of START_ARRAY token\n at [Source: (PushbackInputStream); line: 1, column: 1
How to map the Rest template Json response to object when Json has spaces in parameter keys?
答案1
得分: 3
您的JSON响应是一个对象数组,因为它被包裹在[]
中,所以将数据映射到List<Emp>
中。这里使用了ParameterizedTypeReference
来创建List<Emp>
的TypeReference。
ResponseEntity<List<Emp>> response = restTemplate.exchange(endpointUrl,
HttpMethod.GET, httpEntity,
new ParameterizedTypeReference<List<Emp>>(){});
List<Emp> employees = response.getBody();
英文:
Your JSON response is an array of object since it's wrapped in []
, so map the data into a List<Emp>
. Here used ParameterizedTypeReference
to create the TypeReference of List<Emp>
ResponseEntity<List<Emp>> response = restTemplate.exchange(endpointUrl,
HttpMethod.GET,httpEntity,
new ParameterizedTypeReference<List<Emp>>(){});
List<Emp> employees = response.getBody();
答案2
得分: 0
看起来你正在尝试将数组映射到对象。你可以像这样做:
ResponseEntity<Test[]> response =
restTemplate.getForEntity(
url,
Test[].class);
Test[] employees = response.getBody();
更多信息请查看这篇文章。
英文:
Looks like you are trying to map array to object. You can do something like this
ResponseEntity<Test[]> response =
restTemplate.getForEntity(
url,
Test[].class);
Test[] employees = response.getBody();
For more information check this post
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论