Home  >  Article  >  Java  >  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
Barbara StreisandOriginal
2024-10-26 06:30:30337browse

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>

When deserializing from JSON, you want the format:

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

However, during serialization, it should be formatted as:

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

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>

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>

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>

Prints:

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

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!

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