Java Jackson @JsonIgnoreType Example

1. Introduction

The @JsonIgnoreType annotation in Jackson is used at the class level and marks all the properties of the annotated class to be ignored. This is useful when you have a class-type field in another class and you don't want to serialize or deserialize that particular field's properties, even if they're publicly accessible.

2. Example Steps

1. Create two classes: User and Address.

2. Annotate the Address class with @JsonIgnoreType.

3. Create an instance of a User that has an Address object as one of its fields.

4. Serialize the User instance into a JSON string.

5. Print the JSON string to verify that the properties of the Address object are ignored.

3. Java Jackson @JsonIgnoreType Example

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

public class JsonIgnoreTypeExample {

    public static void main(String[] args) throws Exception {
        // Create a sample User instance with Address
        User user = new User();
        user.setId(1);
        user.setName("John Doe");
        user.setAddress(new Address("123 Street", "City", "12345"));

        ObjectMapper objectMapper = new ObjectMapper();

        // Serialize the User instance to a JSON string and print it
        System.out.println(objectMapper.writeValueAsString(user));
    }

    public static class User {
        private int id;
        private String name;
        private Address address;

        // Getters, setters, and other methods omitted for brevity...

        @Override
        public String toString() {
            return "User{id=" + id + ", name='" + name + "', address=" + address + "}";
        }
    }

    // Use @JsonIgnoreType to ignore all properties of this class during serialization
    @JsonIgnoreType
    public static class Address {
        private String street;
        private String city;
        private String zip;

        // Constructors, getters, setters, and other methods omitted for brevity...
    }
}

Output:

{"id":1,"name":"John Doe"}

4. Step By Step Explanation

In the code, we have two classes: User and Address. The User class has an address field of type Address.

To ensure that the properties of the Address class are ignored during the serialization process, the Address class is annotated with @JsonIgnoreType.

When we serialize an instance of the User class that contains an Address object, the Address object's properties (street, city, and zip) are ignored and not included in the resulting JSON string. As evidenced by the output, only the id and name properties of the User instance are serialized to JSON.


Comments