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
Barbara StreisandOriginal
2024-12-15 04:21:10608browse

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

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;
}

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;
    }
}

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!

Statement:
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