问题@JsonProperty的方法
问题描述:
我目前有我的POJO类用于反序列化json源。问题@JsonProperty的方法
public class OpenBuilding extends Building {
@JsonProperty("BuildingPostCode")
@Override
public String getPostcode() {
return super.getPostcode();
}
}
凡父类是这样
public abstract class Buidling {
protected String postcode;
public String getPostcode() {
return this.postcode;
}
}
我的问题是,字符串邮政编码是没有得到映射的。它在字段上使用注释时有效。但是,由于它是一个继承的字段,并且我有Building的其他子项,它们对同一数据使用不同的属性名称,所以我不能以这种方式实现它。
例如:
public class DirectedBuilding extends Building {
@JsonProperty("Pseudo_PostCode")
@Override
public String getPostcode() {
return super.getPostcode();
}
}
答
也许尝试定义与@JsonCreator
构造。
class Parent {
private final String foo;
public Parent(final String foo) {
this.foo = foo;
}
public String getFoo() {
return foo;
}
}
class Child extends Parent {
@JsonCreator
public Child(@JsonProperty("foo") final String foo) {
super(foo);
}
@JsonProperty("foo")
public String getFoo() {
return super.getFoo();
}
}
public static void main(String[] args) throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
final Child toSerialize = new Child("fooValue");
// Serialize the object to JSON
final String json = objectMapper.writer()
.withDefaultPrettyPrinter()
.writeValueAsString(toSerialize);
// Prints { "foo" : "fooValue" }
System.out.println(json);
// Deserialize the JSON
final Child deserializedChild = objectMapper.readValue(json, Child.class);
// Prints fooValue
System.out.println(deserializedChild.getFoo());
}
它对于这种情况很有用,但是当我需要为10-20个变量做这些时,这种情况变得不太可维护,对于其他一些类,有些情况是正确的 – Flemingjp