我正在处理这个问题。我有这门课:
public class SemaphoreResponse {
ISemaphore semaphore;
StatusHolder statusHolder;
public SemaphoreResponse() {
super();
}
// Getters and setters
}
我想将我的 json 字符串转换为该类,它抛出了这个异常
org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.despegar.henry.automation.services.semaphoreservice.response.ISemaphore, problem: abstract types can only be instantiated with additional type information
at [Source: java.io.StringReader@17a5f5a5; line: 1, column: 2] (through reference chain: com.despegar.henry.automation.services.semaphoreservice.response.SemaphoreResponse["semaphore"])
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.StdDeserializationContext.instantiationException(StdDeserializationContext.java:233)
at org.codehaus.jackson.map.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:60)
at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
所以,我知道发生这种情况是因为“信号量”属性,它是一个接口(interface),所以在该接口(interface)中我知道我必须像这样添加@JsonDeseralize
@JsonDeserialize(as = [class-name].class)
public interface ISemaphore {
public abstract String getId();
public abstract void setId(String id);
public abstract String getOwnerUserId();
}
但这是我的问题。 SemaphoreResponse 中的属性信号量并不总是使用相同的类。因此,我有两个不同的类,称为“MainSemaphore”和“ExecutionSemaphore”,它们都实现了 ISemaphore 接口(interface)。因此,在反序列化时,我想传递我希望接口(interface)适应的类作为参数。
大概是这样的
@JsonDeserialize(as = MainSemaphore.class) or @JsonDeserialize(as = ExecutionSemaphore.class) depending the case
我怎样才能做到这一点?我将感谢您的帮助
最佳答案
除了 ProgrammerBruce 的优秀文章所描述的完整多态处理之外,还有一种更简单的方法来支持简单的接口(interface)/impl、一对一的情况:通过模块进行寄存器映射:
SimpleModule m = new SimpleModule(...);
m.addAbstractTypeMapping(ISemaphore.class, SemaphoreImpl.class);
映射器.registerModule(m);
这将指示 Jackson 始终使用具体类 SemaphoreImpl
反序列化声明为 ISemaphore
的事物。
关于java - Jackson 如何处理接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25021203/