Home > Java > javaTutorial > body text

How to Use Different Names for JSON Properties During Jackson Serialization and Deserialization?

Linda Hamilton
Release: 2024-10-26 12:03:29
Original
238 people have browsed it

How to Use Different Names for JSON Properties During Jackson Serialization and Deserialization?

Using Different Names for JSON Properties During Serialization and Deserialization in Jackson

Serialization and deserialization often require matching field names between JSON and Java classes. However, there may be instances where you want to use different names for the same field during these processes. For instance, consider the following Coordinates class:

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

In this scenario, you might desire the following JSON format for deserialization:

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

Simultaneously, you may prefer a different JSON format for serialization:

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

Initially, attempting to use @JsonProperty annotations on both getter and setter methods may result in an exception:

<code class="java">@JsonProperty("r")
public byte getRed() {
  return red;
}

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

However, this issue can be rectified by ensuring that the method names are distinct. For example:

<code class="java">public byte getR() {
  return red;
}

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

By providing different method names, Jackson interprets them as separate fields. The following test code demonstrates the successful usage of this approach:

<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

The expected output is:

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

The above is the detailed content of How to Use Different Names for JSON Properties During Jackson Serialization and Deserialization?. 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!