Home >Java >javaTutorial >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>
In this scenario, you might desire the following JSON format for deserialization:
<code class="json">{ "red": 12 }</code>
Simultaneously, you may prefer a different JSON format for serialization:
<code class="json">{ "r": 12 }</code>
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>
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>
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>
The expected output is:
Serialization: {"r":5} Deserialization: 25
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!