Java Jackson @JsonProperty Example

1. Introduction

In Java, when working with JSON data and the Jackson library, sometimes the field names in the JSON do not match the names we use in our Java objects. This mismatch can lead to issues when serializing or deserializing JSON. The Jackson @JsonProperty annotation provides a simple solution. It allows us to bind a JSON property name to a Java field name, ensuring seamless serialization and deserialization.

2. Example Steps

1. Create a Java class User with fields that don't directly match the JSON data's property names.

2. Use the @JsonProperty annotation to map JSON property names to Java field names.

3. Serialize and deserialize the User object to demonstrate the annotation's effect.

3. Java Jackson @JsonProperty Example

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

public class JacksonJsonPropertyExample {

    public static void main(String[] args) throws Exception {
        // Initialize JSON string and ObjectMapper
        String jsonString = "{\"first_name\":\"John\",\"last_name\":\"Doe\"}";
        ObjectMapper mapper = new ObjectMapper();

        // Deserialize JSON string to User object
        User user = mapper.readValue(jsonString, User.class);

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

        // Serialize User object back to JSON
        String serializedUser = mapper.writeValueAsString(user);

        // Print the serialized JSON
        System.out.println(serializedUser);
    }
}

class User {
    // Using @JsonProperty to map JSON field names to Java field names
    @JsonProperty("first_name")
    private String firstName;

    @JsonProperty("last_name")
    private String lastName;

    // Getters and setters
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "User [firstName=" + firstName + ", lastName=" + lastName + "]";
    }
}

Output:

User [firstName=John, lastName=Doe]
{"first_name":"John","last_name":"Doe"}

4. Step By Step Explanation

In the provided code, we have a User class with fields named firstName and lastName. However, the JSON string we're working with uses the property names "first_name" and "last_name". To bridge this naming difference, we use the @JsonProperty annotation.

When the ObjectMapper deserializes the JSON string, it correctly maps the JSON properties to the Java fields thanks to the @JsonProperty annotations. Similarly, during serialization, the Java object's field names get converted back to the specified JSON property names.


Comments