gpt4 book ai didi

java - Jackson 定制解串器空编解码器

转载 作者:行者123 更新时间:2023-12-02 04:39:22 24 4
gpt4 key购买 nike

我为我的类型编写了自定义反序列化器,它表示为接口(interface)附件,并且该接口(interface)有两个实现PhotoVideo 。解析时,我使用鉴别器字段从 json 中识别它们。

现在,当 jp.getCodec() 返回 null 时,我遇到问题,导致到空指针异常

为什么会发生这种情况以及如何解决它?

public class AttachmentDeserializer extends StdDeserializer<Attachment> {

ObjectMapper objectMapper = new ObjectMapper();

public AttachmentDeserializer() {
this(null);
objectMapper.registerModule(new Jdk8Module());
}

public AttachmentDeserializer(Class<Attachment> t) {
super(t);
objectMapper.registerModule(new Jdk8Module());
}

@Override
public Attachment deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);

String type = node.get("type").asText();

switch (type) {
case "photo":
return new AttachmentPhoto(
node.get("t").asInt(),
objectMapper.readValue(node.get("photo").traverse(), Photo.class));

case "video":
return new AttachmentVideo(
node.get("t").asInt(),
objectMapper.readValue(node.get("video").traverse(), Video.class));

default:
throw ctxt.weirdStringException("type", Attachment.class, "Unknown discriminator");
}
}
}

附件照片代码:

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class AttachmentPhoto implements Attachment {

private Photo photo;

public Attachments what() {
return Attachments.ATTACHMENT_PHOTO;
}

public String getDiscriminator() {
return "photo";
}

public AttachmentPhoto() {}

public AttachmentPhoto(Photo photo) {
this.photo = photo;
}

public Photo getPhoto() {
return this.photo;
}

public AttachmentPhoto setPhoto(Photo v) {
this.photo = v;
return this;
}

public boolean isAttachmentPhoto() {
return true;
}

public AttachmentPhoto asAttachmentPhoto() {
return this;
}

public boolean isAttachmentVideo() {
return false;
}

public AttachmentVideo asAttachmentVideo() {
throw new IllegalStateException("Not a $stName: " + this);
}

@Override
public boolean equals(Object thatObj) {
if (this == thatObj) return true;

if (!(thatObj instanceof AttachmentPhoto)) return false;

AttachmentPhoto that = (AttachmentPhoto) thatObj;

return this.photo.equals(that.photo);
}

@Override
public String toString() {
return "AttachmentPhoto{" + "photo=" + this.photo + '}';
}
}

最佳答案

您的默认构造函数看起来非常可疑,原因有两个,首先它调用具有 null 类类型的第二个构造函数,然后将 null 类型传递给父类(super class),因此当使用此构造函数时,重写的泛型方法会变得困惑。其次,它没有做任何有用的工作,因为它已经调用了初始化 objectMapper 的另一个构造函数。您应该删除第一个构造函数,只保留类型化的构造函数,并使用它初始化反序列化器。

关于java - Jackson 定制解串器空编解码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56527377/

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