Jackson - @JsonIgnoreProperties 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.

@JsonIgnoreProperties ignores the specified logical properties in JSON serialization and deserialization. It is annotated at the class level.

Ignore Fields at the Class Level using @JsonIgnoreProperties

We can ignore specific fields at the class level, using the @JsonIgnoreProperties annotation and specifying the fields by name:
package net.javaguides.jackson.ignore;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(value = {
    "id",
    "firstName"
})
public class CustomerDTO {
    private final String id;
    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 and printed only "lastName".

References


Comments