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>
We want the following JSON format for deserialization:
<code class="json">{ "red": 12 }</code>
However, for serialization, we need the following format:
<code class="json">{ "r": 12 }</code>
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>
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:
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>
Output:
Serialization: {"r":5} Deserialization: 25
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!