Home > Java > javaTutorial > 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
Release: 2024-10-26 05:52:30
Original
568 people have browsed it

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;
    }
}
Copy after login

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());
Copy after login

Output:

Serialization: {"r":5}
Deserialization: 25
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template