Home > Java > javaTutorial > body text

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

Susan Sarandon
Release: 2024-10-30 02:19:02
Original
940 people have browsed it

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

Handling Property Name Differences for JSON Serialization and Deserialization

In Jackson, it's possible to have different names for a property during serialization and deserialization. Let's consider an example with the following Coordinates class:

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

We want the following JSON format for deserialization:

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

However, for serialization, we need the following format:

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

Solution:

The solution lies in using the @JsonProperty annotation on both the getter and setter methods, ensuring they 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

Note that the method names must be different. Jackson interprets them as references to different properties, rather than the same property with different names.

Additional Notes:

  • For the class attributes, it's advisable to use the appropriate data type (byte in this case) to match the potential values in the JSON payload.
  • The ObjectMapper used for serialization and deserialization can be customized if necessary to configure additional settings.

Test Code:

<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

Output:

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

The above is the detailed content of How to Handle Different Property Names for JSON 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!