杰克逊反序列化为带有可选参数的子类

时间:2021-01-09 11:09:38

I have a question about jackson deserialization, for example we have a parent class foo and subclass bar:

我有一个关于jackson反序列化的问题,例如我们有一个父类foo和子类bar:

@JsonTypeInfo(use = JsonTypeInfo.Id.Name, include = JsonTypeInfo.As.PROPERTY,
property = "bar", visible = true)
@JsonSubTypes( { 
  @Type(value = Foo.class, bar = ""),
  @Type(value = Bar.class, bar = "true")
})
public class Foo{ String value; }

public class Bar extends Foo { boolean bar; }

subclass comes in json format as:

子类以json格式出现:

{ 
"value": "this is some value for bar class",
"bar": "true"
}

but I need jackson to deserialize foo class as well, and it should identify by that boolean value in the child class. Because request might come in as

但是我需要jackson反序列化foo类,它应该通过子类中的boolean值来识别。因为请求可能会以

{ "value": "this is some foo class value" }

1 个解决方案

#1


0  

I hope that will be useful to someone.

我希望这对某人有用。

    @JsonTypeInfo(
        use = JsonTypeInfo.Id.Name, 
      // this will ignore boolean bar value in the parent
        include = JsonTypeInfo.As.EXISTING_PROPERTY,
        property = "bar",
      // this will make a default implementation
        defaultImpl = Foo.class)
    @JsonSubTypes( {@Type(value = Bar.class, name = "true") })
    public class Foo{ String value; }

    public class Bar extends Foo { boolean bar; }

#1


0  

I hope that will be useful to someone.

我希望这对某人有用。

    @JsonTypeInfo(
        use = JsonTypeInfo.Id.Name, 
      // this will ignore boolean bar value in the parent
        include = JsonTypeInfo.As.EXISTING_PROPERTY,
        property = "bar",
      // this will make a default implementation
        defaultImpl = Foo.class)
    @JsonSubTypes( {@Type(value = Bar.class, name = "true") })
    public class Foo{ String value; }

    public class Bar extends Foo { boolean bar; }