Home > Java > javaTutorial > body text

How to Customize JSON Property Names for Different Serialization and Deserialization Using Jackson?

Patricia Arquette
Release: 2024-10-27 06:56:03
Original
729 people have browsed it

How to Customize JSON Property Names for Different Serialization and Deserialization Using Jackson?

Customizing JSON Property Names during Serialization and Deserialization

In object-oriented programming, it is often desirable to manipulate private class fields through method getters and setters while representing the data in a consistent format during serialization and deserialization. Jackson library's annotation-based approach allows us to achieve this by assigning different names to a single property.

Consider a "Coordinates" class with an integer field named "red." We want to serialize JSON objects using the property name "r" while deserializing using the name "red."

To implement this, we can use the @JsonProperty annotation on both the getter and setter methods with different values. However, this approach resulted in an exception:

<code class="json">org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "red"</code>
Copy after login

The issue arises because Jackson assigns the same field name to both the getter and setter methods. To resolve this, we need to 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 approach successfully serializes the object with the property name "r" and deserializes it using the name "red."

<code class="json">Serialization: {"r":5}
Deserialization: 25</code>
Copy after login

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