我已经为此挠头好几个小时了:
Jsckson 反序列化B
但炸弹在C
下面:
B
和C
都是 的子类A
,因此有一个 setter getName
。请注意,大写N
是Name
故意的,这就是我的 JSON 的外观。反序列化C
抱怨 Unrecognized field name Name
,因为B
没关系。
版本 1.7.2
ObjectMapper mapper = new ObjectMapper();
mapper.getDeserializationConfig().addMixInAnnotations(B.class, MixIn.class);
String json = "{\"Name\" : \"13\"}";
B b = m.readValue(json, B.class);
System.out.println(b.getName());
C c = m.readValue(json, C.class);
System.out.println(c.getName());
public class A {
private int id ;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class B extends A {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class C extends A {
private String country;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
@JsonAutoDetect(fieldVisibility = Visibility.NONE,setterVisibility=Visibility.ANY)
abstract class MixIn {
@JsonProperty("Name")
public abstract void setName(String name);
@JsonProperty("Id")
public abstract void setId(int id);
}