package foo;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import com.fasterxml.jackson.annotation.JsonTypeInfo.Id;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
@JsonTypeInfo (include = As.PROPERTY, use = Id.CLASS)
public static abstract class Foo {
@Override
public String toString () {
return "." + this.getClass ().getSimpleName ();
}
//@JsonGetter ("@class")
//private String type () {
// return getClass ().getName ();
//}
}
public static class Bar extends Foo {
private @JsonProperty String lol = "lol";
}
private Map<String, Foo> foo;
private Map<String, Bar> bar;
public static void main (String[] args) throws Exception {
ObjectMapper m = new ObjectMapper ();
Foo f = new Bar ();
System.out.println ("1) " + m.writeValueAsString (f));
System.out.println ("2) " + m.readValue ("{\"@class\":\"foo.Test$Bar\"}", Foo.class));
Object o = m.readValue ("{\"b\":{\"@class\":\"foo.Test$Bar\"}}",
m.constructType (Test.class.getDeclaredField ("bar").getGenericType ()));
o = m.readValue ("{\"f\":{\"@class\":\"foo.Test$Bar\"}}",
m.constructType (Test.class.getDeclaredField ("foo").getGenericType ()));
System.out.println ("3) " + o);
System.out.println ("4) " + m.writeValueAsString (o));
System.out.println ("5) " + m.readValue (m.writeValueAsString (o),
m.constructType (Test.class.getDeclaredField ("foo").getGenericType ())));
}
}
The last sysout does not work unless you comment in the @JsonGetter (the hack to make it work) but then the type information appears twice if you just serialize the object itself - not as being part of a collection
1) {"@class":"foo.Test$Bar","lol":"lol"}
2) .Bar
3) {f=.Bar}
4) {"f":{"lol":"lol"}}
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property '@class' that is to contain type id (for class foo.Test$Foo)
Where the first line is serialization of the object itself, the fourth line is serialization of a map mapping the string "f" to the same object, notice how "@class" property is missing, followed by exception where it cannot deserialize this json back into a map.