如何指定 Jackson 反序列化的默认值

Mic*_*ael 5 java jackson lombok spring-boot

@ResponseBody
@RequestMapping(value="/getUser")
public JSONObject getContent(@ReqeustBody User user) 
Run Code Online (Sandbox Code Playgroud)

这是我的控制器代码。

@Data
public class User{
    private String username = "administrator";
    private String password = "123456";   
    private Integer age = 18;
}
Run Code Online (Sandbox Code Playgroud)

这是我的User班级代码。

{
    "username":"admin",
    "password":"000",
    "age":""
}
Run Code Online (Sandbox Code Playgroud)

当我执行上述POST操作时JSON,我得到的age属性为null

我想用默认值反序列Jackson化空字段(""nullJSON

像这样:

{
    "username":"admin",
    "password":"000",
    "age":18
}
Run Code Online (Sandbox Code Playgroud)

我应该怎么办?

Dav*_*INO 5

您可以定义自定义 getter 属性,在 的情况下设置默认值null

   public Integer getAge() {
        if (age == null) {
            return 18;
        } else {
            return this.age;
        }
    }
Run Code Online (Sandbox Code Playgroud)

请注意,您无法更改该setAge方法,因为在这种情况下不会调用该方法,事实上,没有任何age字段会通知 Jackson 调用该方法。


另一种方法是使用自定义构造函数并将JsonSetter注释与值一起使用Nulls.SKIP

指示应跳过输入空值且不进行赋值的值;这通常意味着该属性将有其默认值

如下:

 public class User {
    @JsonSetter(nulls = Nulls.SKIP)
    private Integer age;

    public User() {
        this.age = 18;
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

存在@JsonSetter于包中com.fasterxml.jackson.annotation,可以使用 maven 作为依赖项导入

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>YOURVERSION</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)