Java Jackson @JsonInclude Example

1. Introduction

When serializing Java objects to JSON using the Jackson library, there might be cases where you want to exclude certain fields based on their values. For instance, excluding null values or default values can make the JSON output cleaner. Jackson provides the @JsonInclude annotation, which allows developers to specify criteria for fields to be included in the serialization process.

2. Example Steps

1. Create a Java class Product with several fields.

2. Apply the @JsonInclude annotation to the class or specific fields to determine their inclusion criteria.

3. Serialize a Product object to demonstrate the effect of the annotation.

3. Java Jackson @JsonInclude Example

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonInclude;

public class JacksonJsonIncludeExample {

    public static void main(String[] args) throws Exception {
        // Create a new Product object with some fields set to default values or null
        Product product = new Product("Laptop", null, 0);

        // Initialize ObjectMapper
        ObjectMapper mapper = new ObjectMapper();

        // Serialize the Product object to JSON
        String jsonString = mapper.writeValueAsString(product);

        // Print the serialized JSON
        System.out.println(jsonString);
    }
}

@JsonInclude(JsonInclude.Include.NON_DEFAULT)
class Product {
    private String name;
    private String description;
    private int price;

    // Constructor, getters, and setters
    public Product(String name, String description, int price) {
        this.name = name;
        this.description = description;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public int getPrice() {
        return price;
    }
}

Output:

{"name":"Laptop"}

4. Step By Step Explanation

In the code provided, we introduced a Product class with fields such as name, description, and price. We then applied the @JsonInclude(JsonInclude.Include.NON_DEFAULT) annotation at the class level. This inclusion criterion ensures that only fields with non-default values (non-null for objects and non-zero for numbers) are included in the serialized JSON output.

After serializing a Product object where the description is null and the price is set to its default value (0), the output JSON only included the name field, demonstrating the effect of the @JsonInclude annotation.


Comments