Jackson - @JsonIgnore 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.
@JsonIgnore is used to ignore the logical property used in serialization and deserialization. @JsonIgnore can be used at setter, getter or field.

Ignore Field at the Field Level using @JsonIgnore

We can also ignore a field directly via the @JsonIgnore annotation directly on the field:
package net.javaguides.jackson.ignore;

import com.fasterxml.jackson.annotation.JsonIgnore;

public class CustomerDTO {

    @JsonIgnore
    private final String id;

    @JsonIgnore
    private final String firstName;
    private final String lastName;

    public CustomerDTO(String id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getId() {
        return id;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return 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 IgnoreFieldTest {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();

        CustomerDTO dtoObject = new CustomerDTO("CUST100", "Tony", "Stark");

        String dtoAsString = mapper.writeValueAsString(dtoObject);

        System.out.println(dtoAsString);
    }
}
Output:
{"lastName":"Stark"}
Note that we have ignored two fields "id" and "firstName" of CustomerDTO using @JsonIgnore annotation and printed only "lastName".

Comments