用Jackson反序列化多态类型

Sam*_*rry 20 json jackson deserialization

如果我有这样的类结构:

public abstract class Parent {
    private Long id;
    ...
}

public class SubClassA extends Parent {
    private String stringA;
    private Integer intA;
    ...
}

public class SubClassB extends Parent {
    private String stringB;
    private Integer intB;
    ...
}
Run Code Online (Sandbox Code Playgroud)

是否有另一种方法来反序列化不同的@JsonTypeInfo呢?在我的父类上使用此批注:

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "objectType")
Run Code Online (Sandbox Code Playgroud)

我宁愿不必强制我的API的客户端包括"objectType": "SubClassA"反序列化子Parent类.

@JsonTypeInfo杰克逊是否提供了一种注释子类并通过唯一属性将其与其他子类区分开来的方式,而不是使用?在上面的示例中,这将是"如果JSON对象"stringA": ...将其反序列化为SubClassA,如果它已将其"stringB": ...反序列化为SubClassB".

Eri*_*pie 17

这感觉像是应该用的东西@JsonTypeInfo,@JsonSubTypes但是我已经选择了文档,并且没有任何可以提供的属性看起来与你所描述的相匹配.

您可以编写一个自定义反序列化器,以@JsonSubTypes非标准方式使用""name"和"value"属性来完成您想要的任务.反序列化器@JsonSubTypes将在您的基类上提供,反序列化器将使用"name"值来检查是否存在属性,如果存在,则将JSON反序列化为"value"属性中提供的类.你的课程看起来像这样:

@JsonDeserialize(using = PropertyPresentDeserializer.class)
@JsonSubTypes({
        @Type(name = "stringA", value = SubClassA.class),
        @Type(name = "stringB", value = SubClassB.class)
})
public abstract class Parent {
    private Long id;
    ...
}

public class SubClassA extends Parent {
    private String stringA;
    private Integer intA;
    ...
}

public class SubClassB extends Parent {
    private String stringB;
    private Integer intB;
    ...
}
Run Code Online (Sandbox Code Playgroud)


ber*_*nie 17

这是我想出的一个解决方案,它在Erik Gillespie的基础上进行了扩展。它完全符合您的要求,并且对我有用。

使用Jackson 2.9

@JsonDeserialize(using = CustomDeserializer.class)
public abstract class BaseClass {

    private String commonProp;
}

// Important to override the base class' usage of CustomDeserializer which produces an infinite loop
@JsonDeserialize(using = JsonDeserializer.None.class)
public class ClassA extends BaseClass {

    private String classAProp;
}

@JsonDeserialize(using = JsonDeserializer.None.class)
public class ClassB extends BaseClass {

    private String classBProp;
}

public class CustomDeserializer extends StdDeserializer<BaseClass> {

    protected CustomDeserializer() {
        super(BaseClass.class);
    }

    @Override
    public BaseClass deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        TreeNode node = p.readValueAsTree();

        // Select the concrete class based on the existence of a property
        if (node.get("classAProp") != null) {
            return p.getCodec().treeToValue(node, ClassA.class);
        }
        return p.getCodec().treeToValue(node, ClassB.class);
    }
}

// Example usage
String json = ...
ObjectMapper mapper = ...
BaseClass instance = mapper.readValue(json, BaseClass.class);
Run Code Online (Sandbox Code Playgroud)

如果您想变得更高级,可以扩展CustomDeserializer以包含一个Map<String, Class<?>>映射属性名称的属性,该属性名称在存在时映射到特定的类。本文介绍了这种方法。

顺便说一下,这里有一个github问题要求这样做:https : //github.com/FasterXML/jackson-databind/issues/1627


M. *_*tin 11

此功能已使用“基于演绎的多态性”添加到 Jackson 2.12 中。要将其应用于您的案例,只需@JsonTypeInfo(use=Id.DEDUCTION)与以下提供的受支持子类型的完整列表一起使用@JsonSubTypes

@JsonTypeInfo(use=Id.DEDUCTION)
@JsonSubTypes({@Type(SubClassA.class), @Type(SubClassB.class)})
public abstract class Parent {
    private Long id;
    ...
}
Run Code Online (Sandbox Code Playgroud)

此功能是根据jackson-databind#43实现的,并在2.12 发行说明中进行了总结:

它基本上允许省略实际的 Type Id 字段或值,只要可以@JsonTypeInfo(use=DEDUCTION)从字段的存在中推导出 ( ) 子类型。也就是说,每个子类型都有一组不同的字段,因此在反序列化期间可以唯一且可靠地检测到类型。

Jackson 创建者撰写的Jackson 2.12 Most Wanted (1/5): Deduction-Based Polymorphism文章中给出了稍长一些的解释。


Sta*_*Man 8

没有.这个功能已经被要求了 - 它可以被称为"类型推断"或"隐含类型" - 但没有人提出一个可行的一般性建议,说明它应该如何工作.很容易想到支持特定案例的特定解决方案的方法,但找出一般解决方案更加困难.

  • 它已在 Jackson 2.12 中使用[多态类型推导](https://github.com/FasterXML/jackson/wiki/Jackson-Release-2.12#polymorphic-type-by-deduction-field-existence) 实现。我已将其扩展为自己的答案:/sf/answers/4631724471/ (2认同)

Nic*_* Ng 6

我的应用程序要求我保留旧的结构,因此我找到了一种在不更改数据的情况下支持多态性的方法。这就是我所做的:

  1. 扩展 JsonDeserializer
  2. 转换为Tree并读取字段,然后返回子类对象

    @Override public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonNode jsonNode = p.readValueAsTree(); 
        Iterator<Map.Entry<String, JsonNode>> ite = jsonNode.fields();
        boolean isSubclass = false;
        while (ite.hasNext()) {
            Map.Entry<String, JsonNode> entry = ite.next();
            // **Check if it contains field name unique to subclass**
            if (entry.getKey().equalsIgnoreCase("Field-Unique-to-Subclass")) {
                isSubclass = true;
                break;
            }
        }
        if (isSubclass) {
            return mapper.treeToValue(jsonNode, SubClass.class);
        } else {
            // process other classes
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)


lpa*_*zic 6

正如其他人指出的那样,在如何工作方面尚未达成共识,因此尚未实施

如果您有Foo类,则当您使用JSON之类的东西时,Bar及其父级FooBar解决方案似乎很明显:

{
  "foo":<value>
}
Run Code Online (Sandbox Code Playgroud)

要么

{
  "bar":<value>
}
Run Code Online (Sandbox Code Playgroud)

但是对于当你得到

{
  "foo":<value>,
  "bar":<value>
}
Run Code Online (Sandbox Code Playgroud)

乍一看,最后一个例子似乎是400 Bad Request的一个明显例子,但实际上有许多不同的方法:

  1. 将其作为400错误请求处理
  2. 按类型/字段的优先级(例如,如果存在字段错误,则其优先级高于某些其他字段foo)
  3. 更复杂的案例2。

我当前适用于大多数情况并尝试利用尽可能多的现有Jackson基础结构的解决方案是(每个层次结构仅需要1个反序列化器):

public class PresentPropertyPolymorphicDeserializer<T> extends StdDeserializer<T> {

    private final Map<String, Class<?>> propertyNameToType;

    public PresentPropertyPolymorphicDeserializer(Class<T> vc) {
        super(vc);
        this.propertyNameToType = Arrays.stream(vc.getAnnotation(JsonSubTypes.class).value())
                                        .collect(Collectors.toMap(Type::name, Type::value,
                                                                  (a, b) -> a, LinkedHashMap::new)); // LinkedHashMap to support precedence case by definition order
    }

    @Override
    public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        ObjectMapper objectMapper = (ObjectMapper) p.getCodec();
        ObjectNode object = objectMapper.readTree(p);
        for (String propertyName : propertyNameToType.keySet()) {
            if (object.has(propertyName)) {
                return deserialize(objectMapper, propertyName, object);
            }
        }

        throw new IllegalArgumentException("could not infer to which class to deserialize " + object);
    }

    @SuppressWarnings("unchecked")
    private T deserialize(ObjectMapper objectMapper,
                          String propertyName,
                          ObjectNode object) throws IOException {
        return (T) objectMapper.treeToValue(object, propertyNameToType.get(propertyName));
    }
}
Run Code Online (Sandbox Code Playgroud)

用法示例:

@JsonSubTypes({
        @JsonSubTypes.Type(value = Foo.class, name = "foo"),
        @JsonSubTypes.Type(value = Bar.class, name = "bar"),
})
interface FooBar {
}
Run Code Online (Sandbox Code Playgroud)
@AllArgsConstructor(onConstructor_ = @JsonCreator)
@Value
static class Foo implements FooBar {
    private final String foo;
}
Run Code Online (Sandbox Code Playgroud)
@AllArgsConstructor(onConstructor_ = @JsonCreator)
@Value
static class Bar implements FooBar {
    private final String bar;
}
Run Code Online (Sandbox Code Playgroud)

杰克逊配置

SimpleModule module = new SimpleModule();
module.addDeserializer(FooBar.class, new PresentPropertyPolymorphicDeserializer<>(FooBar.class));
objectMapper.registerModule(module);
Run Code Online (Sandbox Code Playgroud)

或者如果您使用的是Spring Boot:

@JsonComponent
public class FooBarDeserializer extends PresentPropertyPolymorphicDeserializer<FooBar> {

    public FooBarDeserializer() {
        super(FooBar.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

测试:

    @Test
    void shouldDeserializeFoo() throws IOException {
        // given
        var json = "{\"foo\":\"foo\"}";

        // when
        var actual = objectMapper.readValue(json, FooBar.class);

        // then
        then(actual).isEqualTo(new Foo("foo"));
    }

    @Test
    void shouldDeserializeBar() throws IOException {
        // given
        var json = "{\"bar\":\"bar\"}";

        // when
        var actual = objectMapper.readValue(json, FooBar.class);

        // then
        then(actual).isEqualTo(new Bar("bar"));

    }

    @Test
    void shouldDeserializeUsingAnnotationDefinitionPrecedenceOrder() throws IOException {
        // given
        var json = "{\"bar\":\"\", \"foo\": \"foo\"}";

        // when
        var actual = objectMapper.readValue(json, FooBar.class);

        // then
        then(actual).isEqualTo(new Foo("foo"));
    }
Run Code Online (Sandbox Code Playgroud)