我有一種POJO擴展抽象超類的情況,它使用java.io.Serializable
類型(如下所示)定義類似getId()
和setId()
的方法。每當我反序列化JSON字符串我具體的POJO,我得到以下異常:我怎樣才能使用傑克遜映射器的java.io.Serializable類型字段?
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.io.Serializable, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
at [Source: [email protected]; line: 1, column: 2] (through reference chain: com.demo.jackson.AClass["id"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
at com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:716)
at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:140)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:525)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:99)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:242)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:118)
at com.fasterxml.jackson.databind.ObjectReader._bindAndClose(ObjectReader.java:1270)
at com.fasterxml.jackson.databind.ObjectReader.readValue(ObjectReader.java:897)
如Java代碼:
摘要超類
public abstract class AbstractClass {
protected abstract void setId(final Serializable id);
protected abstract Serializable getId();
}
實現類:AClass
public class AClass extends AbstractClass {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Serializable id) {
this.id = (Long) id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
實現類:BClass
public class BClass extends AbstractClass {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(Serializable id) {
this.id = (String) id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
測試類
public class JsonSerializerTest {
public static void main(String[] args) throws Exception {
final ObjectMapper objectMapper = new ObjectMapper();
serialize(objectMapper);
}
private static void serialize(final ObjectMapper objectMapper) throws Exception {
final String jsonString = "{\"id\":123,\"name\":\"AClass\"}";
final ObjectReader objectReader = objectMapper.reader(AClass.class);
final AClass a = objectReader.readValue(jsonString);
System.out.println(a);
}
}
有人可以提供一些指點?
〜NN
我不認爲可序列化的是一種類型的,它的一個接口。你的抽象getid是可序列化的類型,但是你的具體方法是long型的 – chiliNUT 2014-10-10 19:11:11
是的,我意識到這一點,這是設計的東西。我們的框架團隊提供了這樣的接口和抽象類,而實現則由應用程序開發團隊提供。 – Niranjan 2014-10-10 20:07:06