Skip to content
Advertisement

How do you specify default values for Jackson deserialization

@ResponseBody
@RequestMapping(value="/getUser")
public JSONObject getContent(@ReqeustBody User user) 

Up here is my Controller code.

@Data
public class User{
    private String username = "administrator";
    private String password = "123456";   
    private Integer age = 18;
}

Up here is my User class code.

{
    "username":"admin",
    "password":"000",
    "age":""
}

When I POST the JSON above, I get the age property to be null.

I want Jackson to deserialize the empty fields ("" or null) in JSON with default values.

Like this:

{
    "username":"admin",
    "password":"000",
    "age":18
}

What should I do?

Advertisement

Answer

You can define a custom getter property where setting your default value in case of null.

   public Integer getAge() {
        if (age == null) {
            return 18;
        } else {
            return this.age;
        }
    }

Note that you can’t change the setAge method because it is not invoked in this case, infact there is no age field that will inform Jackson to call that method.


An alternative is to use a custom constructor and use the JsonSetter annotation with the value Nulls.SKIP

Value that indicates that an input null value should be skipped and no assignment is to be made; this usually means that the property will have its default value.

as follow:

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

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

    ...
}

The @JsonSetter is present in package com.fasterxml.jackson.annotation and can be imported as dependency in maven using

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>YOURVERSION</version>
</dependency>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement