【问题标题】:Spring Rest Template Json output mapping to ObjectSpring Rest 模板 Json 输出映射到对象
【发布时间】:2020-11-27 19:26:19
【问题描述】:

当我使用 Spring Rest 模板进行 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: 无法从 [Source: (PushbackInputStream); 的 START_ARRAY 令牌\n 中反序列化 com.pojo.Emp 的实例;行:1,列:1

当Json参数键中有空格时,如何将Rest模板Json响应映射到对象?

【问题讨论】:

  • 你能展示你如何使用 Rest Template 调用 rest API 吗?
  • ResponseEntity resp = restTemplate.exchange(endpointUrl,HttpMethod.GET,httpEntity,EmpApp.class);

标签: java json spring spring-mvc resttemplate


【解决方案1】:

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

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

更多信息请查看this post

【讨论】:

  • 感谢Pankaj,您的回复帮助我了解了使用rest模板处理list obj的方法
【解决方案2】:

您的 JSON 响应是一个对象数组,因为它包含在 [] 中,因此将数据映射到 List&lt;Emp&gt;。这里使用ParameterizedTypeReference创建List&lt;Emp&gt;的TypeReference

ResponseEntity<List<Emp>> response = restTemplate.exchange(endpointUrl, 
                                                  HttpMethod.GET,httpEntity,
                                             new ParameterizedTypeReference<List<Emp>>(){}); 
List<Emp> employees = response.getBody();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-31
    • 2016-07-18
    • 1970-01-01
    • 2016-12-18
    • 2016-11-29
    • 2019-05-27
    • 2012-07-12
    • 1970-01-01
    相关资源
    最近更新 更多