gpt4 book ai didi

java - 与 jackson 重复 JSON 字段

转载 作者:IT老高 更新时间:2023-10-28 12:55:54 26 4
gpt4 key购买 nike

我正在结合 Spring 使用 Jackson 进行 JSON(反)序列化。但是,在某些情况下,我遇到了一个字段两次的问题。

我有一个抽象类:

@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);
}
}
}

一个具体的类扩展了抽象:

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 字段:

{
"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"
}

我已尝试使用 previous 的建议answers使用 @JsonAutoDetect 注释来指定只应使用类上的字段以及在 ObjectMapper 上设置相同的字段,但这并不能解决问题。

注释:

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE,
setterVisibility = JsonAutoDetect.Visibility.NONE, creatorVisibility = JsonAutoDetect.Visibility.NONE,
isGetterVisibility = JsonAutoDetect.Visibility.NONE)

对象映射器:

    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 解决了这个问题。

该项目是开源的,请在此处查看:ANS.java

关于java - 与 jackson 重复 JSON 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18237222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com