jackson-databind: JsonTypeInfo is ignored when serializing a list of annotated object

It seems that JsonTypeInfo is somehow ignored when serializing a list of annotated object. The following is some piece of code describing the situation.

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "clazz")
public class ProjectElement extends BaseObject {
    private Long id = 10L;

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
}

public abstract class AbstractTask extends ProjectElement {
}

public class Task extends AbstractTask {
}

The following two pieces of code produce the results shown:

Task aTask = new Task();
objectMapper.writeValueAsString(aTask)

Outputs: {“id”:10, “clazz”:“Task”}

Task aTask = new Task();
List aList = new ArrayList();
aList.add(aTask);
objectMapper.writeValueAsString(aList);

Outputs: [{“id”:10}]

“clazz” is not produced in the second code. why?

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Comments: 22 (11 by maintainers)

Most upvoted comments

Yes and no: this is due Java Type Erasure. It is missing because element type information is not available to Jackson; all it sees is List<?>, and from that base type (used for finding @JsonTypeInfo) is not available. Base type must be statically accessed, to use uniforma settings, unlike actual content serializer.

So question then is how to pass the extra information needed to detect the type. There are two main alternatives:

  1. Use a helper class like class TaskList extends ArrayList<Task> { } to “save” the type; if so, generic element type is available from super-class (one of oddities of type erasure)
  2. Construct ObjectWriter with specific type: mapper.writerWithType(listTypeConstructedViaTypeFactory).writeValueAsString()

Note that type erasure is only problematic for root values (value directly passed to ObjectMapper). Because of this, I recommend not using Lists or Maps (or any generic types) as root values. They can be made to work, but are more hassle.

I think I’m having the same problem, but how to solve it ? here are the details of my problem : http://stackoverflow.com/questions/37663404/jackson-xml-problems-on-serializing