带有 Spring RestTemplate 的可选嵌套 JSON 对象
Optional nested JSON object with Spring RestTemplate
在 API 中,我尝试与 Spring RestTemplate 一起使用,我收到一个可选字段,如下例所示。
这个可选字段是一个嵌套对象,我想使用嵌套 class 来映射它。
{
"name": "John",
"age": 30
}
{
"name": "John",
"age": 30,
"car": {
"year": 1984,
"color": "red"
}
}
我目前的class定义:
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?
您可以试试下面更新的 class。更改是将内部 class 定义为静态。
public class User {
public static 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;
}
在 API 中,我尝试与 Spring RestTemplate 一起使用,我收到一个可选字段,如下例所示。 这个可选字段是一个嵌套对象,我想使用嵌套 class 来映射它。
{
"name": "John",
"age": 30
}
{
"name": "John",
"age": 30,
"car": {
"year": 1984,
"color": "red"
}
}
我目前的class定义:
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?
您可以试试下面更新的 class。更改是将内部 class 定义为静态。
public class User {
public static 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;
}