Home > Java > javaTutorial > How to Use Different Property Names for Serialization and Deserialization in Jackson?

How to Use Different Property Names for Serialization and Deserialization in Jackson?

Barbara Streisand
Release: 2024-10-26 06:30:30
Original
456 people have browsed it

How to Use Different Property Names for Serialization and Deserialization in Jackson?

Different Property Names for Serialization and Deserialization in Jackson

Can JSON properties have different names during serialization and deserialization? The Jackson library allows this customization.

For instance, consider a Coordinates class:

<code class="java">class Coordinates {
  int red;
}</code>
Copy after login

When deserializing from JSON, you want the format:

<code class="json">{
  "red": 12
}</code>
Copy after login

However, during serialization, it should be formatted as:

<code class="json">{
  "r": 12
}</code>
Copy after login

Implementing this using the @JsonProperty annotation doesn't work as intended because both the getter and setter have different names:

<code class="java">class Coordinates {
    int red;

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

    @JsonProperty("red")
    public void setRed(byte red) {
      this.red = red;
    }
}</code>
Copy after login

This results in the "Unrecognized field "red"" exception.

To address this, use different method names for getter and setter:

<code class="java">public class Coordinates {
    byte red;

    @JsonProperty("r")
    public byte getR() {
      return red;
    }

    @JsonProperty("red")
    public void setRed(byte red) {
      this.red = red;
    }
}</code>
Copy after login

This way, Jackson recognizes the properties as different fields, allowing for different names during serialization and deserialization.

For example:

<code class="java">Coordinates c = new Coordinates();
c.setRed((byte) 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.getR());</code>
Copy after login

Prints:

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

The above is the detailed content of How to Use Different Property Names for Serialization and Deserialization in 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