2013-07-17 54 views
1

我有一个简单的数据对象层次结构,必须将其转换为JSON格式。就像这样:使用@JsonTypeInfo属性发生意外的重复键错误

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "documentType") 
@JsonSubTypes({@Type(TranscriptionDocument.class), @Type(ArchiveDocument.class)}) 
public class Document{ 
    private String documentType; 
    //other fields, getters/setters 
} 

@JsonTypeName("ARCHIVE") 
public class ArchiveDocument extends Document { ... } 

@JsonTypeName("TRANSCRIPTIONS") 
public class TranscriptionDocument extends Document { ... } 

在JSON解析我遇到这样一个错误: Unexpected duplicate key:documentType at position 339.,因为在生成的JSON实际有两种documentType领域。

应该更改什么使JsonTypeName值出现在documentType字段中,没有错误(例如替换其他值)?

杰克逊版本是2.2

回答

2

您的代码不会表现出来,但我敢打赌,你的documentType财产在你Document类的getter。你应该注释此获取与@JsonIgnore像这样:

@JsonIgnore 
public String getDocumentType() { 
    return documentType; 
} 

存在与每个子类有关的隐含documentType属性,所以其在父类相同的属性使其被序列化的两倍。

另一种选择是完全删除getter,但我假设您可能需要它来执行某些业务逻辑,所以@JsonIgnore注释可能是最佳选择。

相关问题