Spring Rest Template将Json输出映射到对象

3
当我使用 Spring RestTemplate 发起 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: Cannot deserialize instance of com.pojo.Emp out of START_ARRAY token\n at [Source: (PushbackInputStream); line: 1, column: 1

如何在 JSON 参数键中包含空格的情况下将 RestTemplate 的 JSON 响应映射到对象?


你能展示一下如何使用 Rest Template 调用 REST API 吗? - Eklavya
ResponseEntity<Emp> resp = restTemplate.exchange(endpointUrl, HttpMethod.GET, httpEntity, EmpApp.class);响应实体 <Emp> resp = restTemplate.exchange(endpointUrl,HttpMethod.GET,httpEntity,EmpApp.class); - sateesh kumar Rayapati
2个回答

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

0

看起来你正在尝试将数组映射到对象。你可以像这样做:

ResponseEntity<Test[]> response =
  restTemplate.getForEntity(
  url,
  Test[].class);
Test[] employees = response.getBody();

欲了解更多信息,请查看此篇文章


谢谢Pankaj,你的回复帮助我理解了使用rest template处理列表对象的方法。 - sateesh kumar Rayapati

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接