On Mon, Jan 28, 2019 at 3:36 PM Jeff Evans <[email protected]> wrote: > > Suppose I have the following class hierarchy and Jackson annotations. > > @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS > public class Base { > private int value; > // snipped getter and setter for "value" field > } > > public class Foo extends Base { > } > > public class Bar extends Base { > } > > I would like to be able to perform all of the following deserialization cases: > > // these both work > Foo foo1 = new ObjectMapper().readValue("{\"@class\": \"Foo\", \"value\": > 1}", Base.class) > Foo foo2 = new ObjectMapper().readValue("{\"@class\": \"Foo\", \"value\": > 1}", Foo.class) > // so does these > Bar bar1 = new ObjectMapper().readValue("{\"@class\": \"Bar\", \"value\": > 1}", Base.class) > Bar bar2 = new ObjectMapper().readValue("{\"@class\": \"Bar\", \"value\": > 1}", Bar.class) > > // these two fail, with com.fasterxml.jackson.databind.JsonMappingException: > Unexpected token (END_OBJECT), expected FIELD_NAME: missing property '@class' > that is to contain type id > Foo foo2 = new ObjectMapper().readValue("{\"value\": 1}", Foo.class) > Bar bar2 = new ObjectMapper().readValue("{\"value\": 1}", Bar.class) > > Ideally, the last two cases should still work. Even though the String > content does not contain the type ID field (the default of @class in this > case), the deserializer should still be able to make use of the fact that I > explicitly requested the class in the readValue calls, via the valueType > parameter (Foo.class and Bar.class respectively). > > Is it possible to configure the deserializer to work in this way? I read > through the Wiki page on polymorphic deserialization a few times but couldn't > figure out how to approach this. I suspect it involves making use of > @JsonTypeResolver and/or @JsonTypeIdResolver, but I'm not sure. Any tips on > how to proceed are greatly appreciated.
This is an open and unsolved issue, basically, and there are a few requests to support use of explicitly passed type information (at least in case of root value being polymorphic). It would be good if things worked as you suggest. Unfortunately I am not aware of working solution, yet, since although it is possible to specify "default type" for case of missing type id, that is considered static so only one default type can be configured (and not dynamically). -+ Tatu +- -- You received this message because you are subscribed to the Google Groups "jackson-user" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To post to this group, send email to [email protected]. For more options, visit https://groups.google.com/d/optout.
