Jackson - Change Name of Field Example

1. Introduction

When serializing or deserializing Java objects using Jackson, there might be situations where the field names in the Java class don't match with the keys in the JSON. Jackson provides a way to customize field names using the @JsonProperty annotation. In this guide, we will explore how to use this annotation to change the name of a field during serialization and deserialization.

2. Example Steps

1. Add the necessary Jackson library dependencies to your project.

2. Create a Java class and annotate the field whose name you want to change using @JsonProperty.

3. Use Jackson's ObjectMapper class to serialize and deserialize the Java object, observing the custom field name.

4. Display the results.

3. Jackson - Change Name of Field Example

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

public class JacksonChangeFieldNameExample {

    public static void main(String[] args) {
        // Initialize ObjectMapper instance.
        ObjectMapper objectMapper = new ObjectMapper();

        // Create a new Person object.
        Person person = new Person("Alice", "Smith", 25);

        try {
            // Serialize the Java object to JSON string.
            String jsonString = objectMapper.writeValueAsString(person);
            System.out.println("Serialized JSON: " + jsonString);

            // Deserialize the JSON string back to Java object.
            Person deserializedPerson = objectMapper.readValue(jsonString, Person.class);
            System.out.println("Deserialized First Name: " + deserializedPerson.getFirstName());

        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    static class Person {
        @JsonProperty("first_name")
        private String firstName;

        @JsonProperty("last_name")
        private String lastName;

        private int age;

        // Constructor, getters, setters, and other methods...
    }
}

Output:

Serialized JSON: {"first_name":"Alice","last_name":"Smith","age":25}
Deserialized First Name: Alice

4. Step By Step Explanation

1. We define a Person class with three attributes: firstName, lastName, and age. We use the @JsonProperty annotation to specify that during serialization and deserialization, firstName should map to first_name in the JSON and lastName should map to last_name.

2. The ObjectMapper is initialized, which is Jackson's primary class for serialization and deserialization.

3. We create a new instance of the Person class and then serialize it into a JSON string. As observed in the output, the field names in the JSON are altered according to our @JsonProperty annotations.

4. We then deserialize the JSON string back into a Person object and display the firstName to verify that the deserialization also respects our field name customizations.


Comments