序列化和反序列化过程中 JSON 属性的不同名称 [英] Different names of JSON property during serialization and deserialization
问题描述
是否有可能:在类中有一个字段,但在 Jackson 库中的序列化/反序列化过程中使用不同的名称?
Is it possible: to have one field in class, but different names for it during serialization/deserialization in Jackson library?
例如,我有Coordiantes"类.
For example, I have class "Coordiantes".
class Coordinates{
int red;
}
对于从 JSON 反序列化希望有这样的格式:
For deserialization from JSON want to have format like this:
{
"red":12
}
但是当我将对象序列化时,结果应该是这样的:
But when I will serialize object, result should be like this one:
{
"r":12
}
我试图通过在 getter 和 setter(具有不同的值)上应用 @JsonProperty
注释来实现这一点:
I tried to implement this by applying @JsonProperty
annotation both on getter and setter (with different values):
class Coordiantes{
int red;
@JsonProperty("r")
public byte getRed() {
return red;
}
@JsonProperty("red")
public void setRed(byte red) {
this.red = red;
}
}
但我有一个例外:
org.codehaus.jackson.map.exc.UnrecognizedPropertyException:无法识别的字段红色"
org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "red"
推荐答案
刚刚测试,这有效:
public class Coordinates {
byte red;
@JsonProperty("r")
public byte getR() {
return red;
}
@JsonProperty("red")
public void setRed(byte red) {
this.red = red;
}
}
这个想法是方法名应该不同,所以jackson将其解析为不同的字段,而不是一个字段.
The idea is that method names should be different, so jackson parses it as different fields, not as one field.
这里是测试代码:
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());
结果:
Serialization: {"r":5}
Deserialization: 25
这篇关于序列化和反序列化过程中 JSON 属性的不同名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!