与Jackson重复的JSON字段 [英] Duplicate JSON Field with Jackson
问题描述
我正在与Spring结合使用Jackson进行JSON(反)序列化.但是,在某些情况下,我遇到了一个字段为两次的问题.
I am using Jackson for JSON (de)serialization in conjunction with Spring. However I am having an issue with a field being twice in some cases.
我有一个抽象类:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "mimeType")
@JsonSubTypes({
@JsonSubTypes.Type(value = ImageBookmarkJsonModel.class, name = "image/jpeg"),
@JsonSubTypes.Type(value = EpubBookmarkJsonModel.class, name = "application/epub+zip")
})
public abstract class AbstractBookmarkJsonModel extends AbstractJsonModel {
protected String mimeType;
// Removed other fields for brevity
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
@Override
public String toString() {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(this);
} catch (IOException e) {
throw new IllegalStateException("Cannot convert object of type " + this.getClass().toString() + " to JSON", e);
}
}
}
一个具体的类扩展了抽象:
And a concrete class extend the abstract:
public class EpubBookmarkJsonModel extends AbstractBookmarkJsonModel {
private static final long serialVersionUID = 1L;
// Removed other fields for brevity
public EpubBookmarkJsonModel() {
this.mimeType = "application/epub+zip";
}
}
问题是,当我序列化此JSON时,我得到一个重复的mimeType
字段:
The problem is that when I serialize this JSON, I get a duplicate mimeType
field:
{
"mimeType": "application/epub+zip",
"mimeType": "application/epub+zip",
"userId": 24,
"acid": "ACID-000000000029087",
"added": "2013-08-14T12:02:17Z",
"epubBookmarkId": 34,
"cfi": "epubcfi(/6/4!/2/68)",
"context": "CONTEXT"
}
我尝试使用答案使用@JsonAutoDetect
批注指定仅使用类上的字段以及在ObjectMapper
上设置相同的字段,但这不能解决问题.
I have tried using the recommendation of previous answers to use the @JsonAutoDetect
annotation to specify that only fields on a class should be used as well as setting the same on the ObjectMapper
, however this does not fix the problem.
注释:
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)
ObjectMapper:
ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE);
推荐答案
我通过使用@JsonTypeInfo批注中的JsonTypeInfo.As.EXISTING_PROPERTY
解决了这个问题.
I solved this by using the JsonTypeInfo.As.EXISTING_PROPERTY
in the @JsonTypeInfo annotation.
该项目是开源的,请在此处查看:ANS.java
The project is open source, check it out here: ANS.java
这篇关于与Jackson重复的JSON字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!