Home > Java > javaTutorial > How Can I Skip Null Values When Serializing Objects with Jackson?

How Can I Skip Null Values When Serializing Objects with Jackson?

Barbara Streisand
Release: 2024-12-15 04:21:10
Original
607 people have browsed it

How Can I Skip Null Values When Serializing Objects with Jackson?

Jackson: Skipping Null Values during Serialization

When serializing objects using Jackson, it can be desirable to exclude fields with null values to optimize data size and improve readability. To this end, Jackson offers two methods to achieve this behavior:

1. Global Configuration:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

//...

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); // disable serialization of null values
Copy after login

This setting applies globally to all serialization operations performed by the ObjectMapper instance.

2. @JsonInclude Annotation:

The @JsonInclude annotation can be applied to specific fields or classes to customize their serialization behavior. For example:

import com.fasterxml.jackson.annotation.JsonInclude;

//...

@JsonInclude(JsonInclude.Include.NON_NULL)
public class SomeClass {
    private String someValue;
}
Copy after login

This annotation instructs Jackson to exclude the someValue field from serialization if its value is null.

Alternatively, the @JsonInclude annotation can be used on the getter method of the field:

import com.fasterxml.jackson.annotation.JsonInclude;

//...

public class SomeClass {
    private String someValue;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    public String getSomeValue() {
        return someValue;
    }
}
Copy after login

This approach allows the field to be serialized only when its value is not null.

The above is the detailed content of How Can I Skip Null Values When Serializing Objects with Jackson?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template