Jackson - @JsonIgnoreType Example

In this post, we will see how to ignore certain fields when serializing an object to JSON using Jackson @JsonIgnore annotation with an example.

@JsonIgnoreType is annotated at the class level and it ignores the complete class.

Ignore all Fields by Type using @JsonIgnoreType

We can also ignore all fields of a specified type, using the @JsonIgnoreType annotation. If we control the type, then we can annotate the class directly:
@JsonIgnoreType
public static class Name {
    public String firstName;
    public String lastName;
    public Name(String firstName, String lastName) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
Here is the complete code:
package net.javaguides.jackson.ignore;

import com.fasterxml.jackson.annotation.JsonIgnoreType;

public class UserDTO {

    public int id;
    public Name name;


    public UserDTO(int id, Name name) {
        super();
        this.id = id;
        this.name = name;
    }

    @JsonIgnoreType
    public static class Name {
        public String firstName;
        public String lastName;
        public Name(String firstName, String lastName) {
            super();
            this.firstName = firstName;
            this.lastName = lastName;
        }
    }
}
Let's test above code with a main() method, note that after the object is written to JSON, the field is indeed not part of the output:
package net.javaguides.jackson.ignore;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonIgnoreTypeTest {

    public static void main(String[] args) throws JsonProcessingException {
        UserDTO.Name name = new UserDTO.Name("John", "Doe");
        UserDTO user = new UserDTO(1, name);

        String result = new ObjectMapper()
            .writeValueAsString(user);

        System.out.println(result);
    }
}
Output:
{"id":1}
Note that the Name class field is ignored by using @JsonIgnoreType annotation.

References



Comments