I am working with a hierarchy of objects described as follows:
A
B extends A
C extends B
D extends B
E extends C
F extends A and contains a reference to A
The annotation for class A is defined as:
@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS,include=JsonTypeInfo.As.PROPERTY,property="@class")
When trying to deserialize a JSON array containing objects that extend class A, an error is thrown:
org.codehaus.jackson.map.JsonMappingException: Unexpected token (START_OBJECT), expected VALUE_STRING: need JSON String that contains type id (for subtype of java.util.Collection)
The JSON string is generated using the toString() method of a Set parametrized to type A. The serialization of A into JSON is achieved through the following code:
ObjectMapper objectMapper=new ObjectMapper();
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS);
String res="";
try {
res = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(t);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
The code used to deserialize the JSON array (representing the aforementioned Set) is:
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS);
Collection<T> results=null;
try {
results = mapper.readValue(json, TypeFactory.defaultInstance().constructParametricType(Collection.class, clazz ) );
} catch (JsonParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return results;
An example of the JSON format it processes looks like:
"[{
"@class" : "pack1.pack2.MyClass",
"id" : null,
"f1" : "",
"f2" : 0.9933817827,
...
"featureIndicator" : false
}]"
This excerpt of JSON includes only specific objects from a sample Java Set.