我有一个类,我想说Person
,我希望使用Jackson从JSON填充,但属性名称因来源而异。以下是代码当前的显示方式:
class Person {
protected String firstName;
protected String lastName;
protected String address;
public abstract void setFirstName(String firstName);
public abstract void setLastName(String lastName);
public abstract void setAddress(String address);
// getters etc.
}
class PersonFormat1 extends Person {
@Override
@JsonProperty("firstName")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
@JsonProperty("lastName")
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override("address")
public void setAddress(String address) {
this.address = address;
}
}
class PersonFormat2 extends Person {
@Override
@JsonProperty("fName")
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
@JsonProperty("lName")
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override("addr")
public void setAddress(String address) {
this.address = address;
}
}
如您所见,PersonFormat1
和PersonFormat2
在结构上是相同的,但我需要不同的子类才能指定不同的属性名称。
是否有某种方法可以强制执行模型而不需要重新声明和重新实现每种方法的样板?
答案 0 :(得分:1)
一种方法是使用 PropertyNamingStrategy http://wiki.fasterxml.com/PropertyNamingStrategy
这是一个很好的简单演示如何使用它Link to How to Use PropertyNamingStrategy in Jackson
另一种是使用 MixInAnnotations http://wiki.fasterxml.com/JacksonMixInAnnotations
使用MixInAnnotations
,您只需创建一个Person
类,并为任何其他替代属性名称设置创建Mixin。
public static void main(String[] args) throws IOException {
ObjectMapper mapper1 = new ObjectMapper();
String person1 = "{\"firstName\":null,\"lastName\":null,\"address\":null}";
Person deserialized1 = mapper1.readValue(person1,Person.class);
ObjectMapper mapper2 = new ObjectMapper();
mapper2.addMixIn(Person.class, PersonMixin.class);
String person2 = "{\"fName\":null,\"lName\":null,\"addr\":null}";
Person deserialized2 = mapper2.readValue(person2,Person.class);
}
public static class Person {
@JsonProperty("firstName")
String firstName;
@JsonProperty("lastName")
String lastName;
@JsonProperty("address")
String address;
}
public class PersonMixin {
@JsonProperty("fName")
String firstName;
@JsonProperty("lName")
String lastName;
@JsonProperty("addr")
String address;
}