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 
<https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization>
 
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.

-- 
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.

Reply via email to