Java Jackson @JsonIgnoreProperties Example

1. Introduction

The @JsonIgnoreProperties annotation in Jackson is a class-level annotation that allows us to specify which properties of a JSON input should be ignored during the deserialization process. It's particularly useful when the incoming JSON has some fields that we don't want to map to our Java object or vice versa during serialization.

2. Example Steps

1. Create a User class with fields: id, username, and password.

2. Annotate the User class with @JsonIgnoreProperties to specify that the password field from incoming JSON should be ignored during deserialization.

3. Deserialize a sample JSON string that includes the password field.

4. Print the deserialized User object to verify that the password field was not mapped.

3. Java Jackson @JsonIgnoreProperties Example

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

public class JsonIgnorePropertiesExample {

    public static void main(String[] args) throws Exception {
        // Sample JSON input
        String json = "{\"id\":1, \"username\":\"john_doe\", \"password\":\"secret\"}";

        ObjectMapper objectMapper = new ObjectMapper();

        // Deserialize the JSON string and print the result
        System.out.println(objectMapper.readValue(json, User.class));

    // Use @JsonIgnoreProperties to specify properties to be ignored during deserialization
    public static class User {
        private int id;
        private String username;
        // No need to add any annotations to the field itself
        private String password;

        // Getters, setters and toString omitted for brevity...

        public String toString() {
            return "User{id=" + id + ", username='" + username + "', password='" + password + "'}";


User{id=1, username='john_doe', password='null'}

4. Step By Step Explanation

In the code, the User class is defined with three fields: id, username, and password. The goal is to ensure that the password from the incoming JSON is not deserialized into our Java object for security reasons.

To achieve this, the User class is annotated with @JsonIgnoreProperties({"password"}), indicating that the password property in the JSON should be ignored during the deserialization process.

As observed in the output, when the sample JSON string is deserialized using Jackson's ObjectMapper, the password property from the JSON is not mapped to the User object's password field, and its value remains null in the deserialized object.