Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson: @JsonTypeInfo missing in Arrays

I found some strange behavior of the Jackson JSON Processor library and i am curious whether this is intentional or a bug. Please have 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));

Output:

{"@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

Do i miss something or should i file a bug report?

like image 789
nutlike Avatar asked Jan 29 '13 11:01

nutlike


1 Answers

This is expected behavior. When traversing an object graph for serialization, Jackson uses the declared type of an object when determining what type information to include. The elements in objects have declared type Object, which you haven't told Jackson to include any type information for.

Jackson only looks at the runtime type of the top-level argument to writeValueAsString, because the method argument has type Object; it's not possible in Java to know the declared type of an object passed as an argument to a method (even with generics, thanks to type erasure), so your first two examples (writeValueAsString(nut) and writeValueAsString(object) are effectively identical).

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

like image 129
Miles Avatar answered Sep 21 '22 10:09

Miles