Java Jackson @JsonSetter Example

1. Introduction

Jackson's @JsonSetter annotation allows customization of the JSON property name during deserialization. This is beneficial when the JSON field names don't align with the Java field names and you want to map a JSON property to a specific Java field or setter method.

2. Example Steps

1. Create a User class with fields firstName and userAge.

2. Annotate the setter methods with @JsonSetter to indicate custom JSON property names.

3. Deserialize a JSON string that has different field names than our Java class.

4. Print the deserialized User object to verify that the fields were correctly set.

3. Java Jackson @JsonSetter Example

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonSetterExample {

    public static void main(String[] args) throws Exception {
        // Sample JSON input with field names that don't align with our Java fields
        String json = "{\"first_name\":\"Alice\",\"age\":25}";

        // Use Jackson to deserialize the JSON input
        ObjectMapper objectMapper = new ObjectMapper();
        User user = objectMapper.readValue(json, User.class);

        // Print the resulting object
        System.out.println(user);
    }

    public static class User {
        private String firstName;
        private int userAge;

        public String getFirstName() {
            return firstName;
        }

        @JsonSetter("first_name")
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public int getUserAge() {
            return userAge;
        }

        @JsonSetter("age")
        public void setUserAge(int userAge) {
            this.userAge = userAge;
        }

        @Override
        public String toString() {
            return "User{firstName='" + firstName + "', userAge=" + userAge + '}';
        }
    }
}

Output:

User{firstName='Alice', userAge=25}

4. Step By Step Explanation

In this example, we have a User class with fields firstName and userAge. However, the provided JSON string uses different property names (first_name and age). To bridge this discrepancy, we utilize the @JsonSetter annotation on the setter methods, specifying the exact JSON property name we're expecting.

The setFirstName method is annotated with @JsonSetter("first_name"), instructing Jackson to use this method when encountering the first_name property in the JSON. Similarly, the setUserAge method is annotated to handle the age property.

During deserialization, Jackson identifies the annotated setters and correctly sets the fields in the User class based on the provided JSON, ensuring that the Java object reflects the data in the JSON string.


Comments