I’m experementing with Jackson serialization/deserialization.
For instance, I have such class:
class Base{
String baseId;
}
And I want to serialize List objs;
To do it with jackson, I need to specify a list’s elements real type, due to the java type erasure.
This code will work:
List<Base> data = getData();
return new ObjectMapper().writerWithType(TypeFactory.collectionType(List.class, Base.class)).writeValueAsString(data);
Now, I want to serialize more complex class:
class Result{
List<Base> data;
}
How should I tell Jackson to properly serialize this class?
Just
The type of the list won’t be lost due to type erasure in the same way it would be in the first example.
Note that for vanilla serialization of a list or generic list, it’s not necessary to specify the list component types, as demonstrated in the example in the original question. All three of the following example serializations represent the
List<Bar>with the exact same JSON.A typed writer is useful when serializing with additional type information. Note how the
json1andjson3outputs below differ.