【发布时间】:2020-03-28 16:08:46
【问题描述】:
在我尝试与 Spring RestTemplate 一起使用的 API 中,我收到了一个可选字段,如下例所示。 这个可选字段是一个嵌套对象,我想使用一个嵌套类来映射它。
{
"name": "John",
"age": 30
}
{
"name": "John",
"age": 30,
"car": {
"year": 1984,
"color": "red"
}
}
我目前的班级定义:
public class User {
public class Car {
@Getter
@Setter
public String color;
@Getter
@Setter
public Integer year;
}
@Getter
@Setter
public String name;
@Getter
@Setter
public Integer age;
@Getter
@Setter
public Car car;
}
通过调用:
ResponseEntity<User> response = restTemplate.exchange("http://....", HttpMethod.POST, request, User.class);
我得到以下异常:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of '....User$Car' (although at least one Creator exists): can only instantiate non-static inner class by using default, no-argument constructor
如果节点存在于 json 中,我如何拥有 null 或使用 Car 类实例化的 car 属性?
【问题讨论】:
标签: json spring resttemplate