简体   繁体   中英

Jackson deserialization to subclass with optional parameter

I have a question about jackson deserialization, for example we have a parent class foo and subclass 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:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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