是否可能:在类中有一个字段,但在Jackson库中序列化/反序列化期间为它取不同的名称?
例如,我有一个类“coordindiantes”。
class Coordinates{
int red;
}
对于JSON的反序列化,希望有这样的格式:
{
"red":12
}
但是当我序列化对象时,结果应该是这样的:
{
"r":12
}
我试图通过在getter和setter上应用@JsonProperty注释来实现这一点(具有不同的值):
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。exx . unrecognizedpropertyexception:无法识别的字段“red”
可以有普通的getter/setter对。您只需要在@JsonProperty中指定访问模式
下面是单元测试:
public class JsonPropertyTest {
private static class TestJackson {
private String color;
@JsonProperty(value = "device_color", access = JsonProperty.Access.READ_ONLY)
public String getColor() {
return color;
};
@JsonProperty(value = "color", access = JsonProperty.Access.WRITE_ONLY)
public void setColor(String color) {
this.color = color;
}
}
@Test
public void shouldParseWithAccessModeSpecified() throws Exception {
String colorJson = "{\"color\":\"red\"}";
ObjectMapper mapper = new ObjectMapper();
TestJackson colotObject = mapper.readValue(colorJson, TestJackson.class);
String ser = mapper.writeValueAsString(colotObject);
System.out.println("Serialized colotObject: " + ser);
}
}
我得到的输出如下:
Serialized colotObject: {"device_color":"red"}