如何处理杰克逊的接口?

时间:2014-07-29 17:13:51

标签: java json serialization jackson abstract

我正在处理这个问题。我有这门课:

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)

所以,据我所知,这是因为“信号量”属性,这是一个接口,所以进入该接口,我知道我必须像这样添加@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。因此,在deserealization的时候,我想传递我希望接口适应的类作为参数。

这就像是

@JsonDeserialize(as = MainSemaphore.class) or @JsonDeserialize(as = ExecutionSemaphore.class) depending the case

我怎么能这样做?非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

除了完整的多态处理,由ProgrammerBruce的优秀文章描述,还有一种更简单的方法来支持简单的接口/ impl,一对一,案例:通过模块的寄存器映射:

SimpleModule m = new SimpleModule(...); m.addAbstractTypeMapping(ISemaphore.class, SemaphoreImpl.class); mapper.registerModule(m);

这将指示Jackson始终使用具体的类ISemaphore将事件反序列化为SemaphoreImpl