使用@JsonTypeInfo属性发生意外的重复键错误 [英] Unexpected duplicate key error using @JsonTypeInfo property
问题描述
我有一个简单的数据对象层次结构,必须转换为JSON格式。像这样:
I have a simple hierarchy of data objects, which have to be converted to JSON format. Like this:
@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解析时,我遇到类似这样的错误:
意外重复键:位置339处的documentType。
,因为在生成的JSON中实际上有两个 documentType
fields。
Upon JSON parsing I encounter errors like this one:
Unexpected duplicate key:documentType at position 339.
, because in the generated JSON there are actually two documentType
fields.
应该更改为什么 JsonTypeName
值出现在 documentType
字段中,没有错误(例如替换其他值)?
What should be changed to make JsonTypeName
value appear in documentType
field, without an error (eg replacing the other value)?
杰克逊版本为2.2
推荐答案
你的代码没有显示,但我打赌你的文件中有一个吸气剂
documentType
属性的类。你应该用 @JsonIgnore
注释这个getter,如下所示:
Your code doesn't show it, but I bet you have a getter in your Document
class for the documentType
property. You should annotate this getter with @JsonIgnore
like so:
@JsonIgnore
public String getDocumentType() {
return documentType;
}
隐含的 documentType
与每个子类关联的属性,因此在父类中具有相同的属性会导致它被序列化两次。
There is an implicit documentType
property associated with each subclass, so having the same property in the parent class causes it to be serialized twice.
另一种选择是完全删除getter,但是我假设您可能需要它来处理某些业务逻辑,因此 @JsonIgnore
注释可能是最佳选择。
Another option would be to remove the getter altogether, but I assume you might need it for some business logic, so the @JsonIgnore
annotation might be the best option.
这篇关于使用@JsonTypeInfo属性发生意外的重复键错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!