📜  jackson ignore null - Java (1)

📅  最后修改于: 2023-12-03 15:15:54.045000             🧑  作者: Mango

Jackson Ignore Null - Java

Jackson is a widely used Java library for handling JSON data. It provides various annotations to configure how JSON data is mapped to Java objects and vice versa. One such annotation is @JsonIgnore, which can be used to ignore a specific field during serialization and deserialization. However, sometimes you may want to ignore all null values in the JSON data. In this case, you can use the @JsonInclude annotation with the Include.NON_NULL value.

Ignore null values during serialization

To ignore null values during serialization, you can add the @JsonInclude annotation above your class definition and set the value to Include.NON_NULL.

@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyData {
    private String name;
    private Integer age;
    private String address;

    // getters and setters
}

In the above example, if the age field is null, it will be ignored during serialization.

Ignore null values during deserialization

To ignore null values during deserialization, you can add the @JsonInclude annotation above your class definition and set the value to Include.NON_NULL. Additionally, you need to enable the DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES feature.

@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyData {
    private String name;
    private int age;
    private String address;

    // getters and setters
}
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true);

MyData data = mapper.readValue(jsonString, MyData.class);

In the above example, if the age field is null, it will be set to the default value of 0 since it is a primitive type. If the DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES feature is not enabled, the age field will be set to null.

Conclusion

Using the @JsonInclude annotation with the Include.NON_NULL value is a simple and effective way to ignore null values during serialization and deserialization with Jackson.