Home  >  Article  >  Java  >  How to Achieve Different Property Names for Serialization and Deserialization with Jackson?

How to Achieve Different Property Names for Serialization and Deserialization with Jackson?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 05:52:30470browse

How to Achieve Different Property Names for Serialization and Deserialization with Jackson?

JSON Serialization/Deserialization with Different Property Names

Jackson library offers the flexibility to specify different names for a property during serialization and deserialization. Consider the following scenario:

You have a class named "Coordinates" with a field "red". During deserialization from JSON, you want this field to be mapped to the property name "red". However, during serialization, you want the property name to be "r".

Solution

To achieve this, you can use the @JsonProperty annotation along with different method names for the getter and setter:

public class Coordinates {
    private int red;

    @JsonProperty("r")
    public int getRed() {
        return red;
    }

    @JsonProperty("red")
    public void setRed(int red) {
        this.red = red;
    }
}

By using different method names for the getter and setter, Jackson recognizes them as distinct properties. During deserialization, it maps the JSON property "red" to the setter with the @JsonProperty("red") annotation. During serialization, it uses the getter with the @JsonProperty("r") annotation to retrieve the value and serialize it as the property "r".

Example

To illustrate this behavior, consider the following test code:

Coordinates c = new Coordinates();
c.setRed(5);

ObjectMapper mapper = new ObjectMapper();
System.out.println("Serialization: " + mapper.writeValueAsString(c));

Coordinates r = mapper.readValue("{\"red\":25}", Coordinates.class);
System.out.println("Deserialization: " + r.getRed());

Output:

Serialization: {"r":5}
Deserialization: 25

As you can see, the property name "red" is used during deserialization, while the property name "r" is used during serialization.

The above is the detailed content of How to Achieve Different Property Names for Serialization and Deserialization with Jackson?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn