简体   繁体   English

使用杰克逊处理JSON反序列化中缺少的类

[英]Handling missing classes in json deserialization using jackson

Using Jackson, I am serializing an object to JSON. 使用Jackson,我将一个对象序列化为JSON。 Inside the JSON-Serialized parent object is an object that is some subtype of an abstract class. JSON序列化的父对象内部是一个对象,该对象是抽象类的某些子类型。

@JsonTypeInfo(
        use = JsonTypeInfo.Id.CLASS,
        include = JsonTypeInfo.As.PROPERTY,
        property = "@class")

public abstract class AbstractSupertype{...}

public class ActualSerializedSubObject extends AbstractSypertype{...}

My object graph would then look something like 我的对象图将看起来像

Parent object
|-> ChildObject
   |->ActualSerializedSubObject (Or some other subtype of AbstractSupertype)

The problem is that for various OSGi-related reasons, the specific subtype and object was serialized with, is not always available when it is later deserialized to an object. 问题在于,由于各种与OSGi相关的原因,特定的子类型和对象被序列化后,在以后反序列化为对象时并不总是可用。 When that is the case Jackson rightly throws an exception com.fasterxml.jackson.databind.JsonMappingException . 在这种情况下,Jackson正确地抛出了com.fasterxml.jackson.databind.JsonMappingException异常。

What i would like, is that for this particular field, when the class in not found, an exception is not thrown, but the field is instead set to null, and the parsing is allowed to continue. 我想要的是,对于该特定字段,当未找到该类时,不会引发异常,但是该字段设置为null,并且允许继续解析。 Any remaining json for that object should be discarded, and replaced with a null. 该对象的所有剩余json应该被丢弃,并替换为null。

Parent object
|-> ChildObject
   |->null (No exception is thrown, the object is set set null)

Is this possible, and how? 这有可能吗?

I think you want to use this configuration option : 我认为您想使用此配置选项

mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false);

It will replace unknown sub-type to null. 它将未知的子类型替换为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM