Jackson: @JsonTypeInfo missing in arrays

I found the strange behavior of the Jackson JSON processor library and I wonder if this is intentional or an error. Take a look at the code below:

@JsonTypeInfo(use = Id.NAME) public class Nut {} 

...

 ObjectMapper mapper = new ObjectMapper(); Nut nut = new Nut(); Object object = new Nut(); Nut[] nuts = new Nut[] { new Nut() }; Object[] objects = new Object[] { new Nut() }; System.out.println(mapper.writeValueAsString(nut)); System.out.println(mapper.writeValueAsString(object)); System.out.println(mapper.writeValueAsString(nuts)); System.out.println(mapper.writeValueAsString(objects)); 

Conclusion:

 {"@type":"Nut"} {"@type":"Nut"} [{"@type":"Nut"}] [{}] 

What I expect (and want) is the following:

 {"@type":"Nut"} {"@type":"Nut"} [{"@type":"Nut"}] [{"@type":"Nut"}] // <<< type information included 

Am I missing something or should I post a bug report?

+6
source share
1 answer

This is the expected behavior. When moving an object graph for serialization, Jackson uses the declared object type to determine what information should be included in the type. Elements in objects declared an Object type, which you did not tell Jackson to include any type information for.

Jackson only considers the execution type of the top-level argument writeValueAsString , because the method argument is of type Object ; it is impossible in Java to know the declared type of an object, passed as an argument to a method (even with generics, due to type erasure), so your first two examples ( writeValueAsString(nut) and writeValueAsString(object) practically identical).

More information here: http://jackson-users.ning.com/forum/topics/mapper-not-include-type-information-when-serializing-object-why

+4
source

All Articles