1

我有一个简单的数据对象层次结构,必须将其转换为 JSON 格式。像这样:

@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

4

1 回答 1

2

您的代码没有显示它,但我敢打赌,您的Document班级中有一个用于该documentType属性的吸气剂。你应该这样注释这个getter @JsonIgnore

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

每个子类都有一个隐含的documentType属性,因此在父类中具有相同的属性会导致它被序列化两次。

另一种选择是完全删除 getter,但我假设您可能需要它用于某些业务逻辑,因此@JsonIgnore注释可能是最佳选择。

于 2013-07-29T19:19:54.730 回答