How do i tell jackson to use a different serializer for each of the Generic collection type.
I have a CustomProductsSerializer and a CustomClientsSerializer
public class ProductsListSerializer extends JsonSerializer<List<Products>>{
// logic to insert __metadata , __count into json
public void serialize(List<Products> value, JsonGenerator jgen, SerializerProvider provider) {
.... .... ....
}
// always returns ArrayList.class
public Class<List<Instrument>> handledType() {
Class c = var.getClass();
return c;
}
}
public class CustomClientsSerializer extends JsonSerializer<List<Clients>>{
// logic to insert __metadata , __count into json
public void serialize(List<Clients> value, JsonGenerator jgen, SerializerProvider provider){
.... .... ....
}
.... .... ....
// always returns ArrayList.class
public Class<List<Clients>> handledType() {
Class c = var.getClass();
return c;
}
}
I have registered both the serializers using SimpleModule.
The problem is, since handledType in both cases returns ArrayList.class, serialization of clients below fail with a class cast exception.
List<Clients> clients;
// code to get clients from database.
String jsonString = mapper.writeValueAsString(clients);
Question is how to tell jackson about which serializer to use ?
I am using jackson as the json serializer with resteasy.
–Edit in response to @HiJon89
I have a business object which returns ‘List’ and another which returns List. The way I need is when the Busines Object returns a ‘List’ then ProductsListSerializer should be used for the whole List. and When Business Object returns ‘List the CustomClientsSerializer should be used for the whole List. In my use-case I append additional elements to the serialized json ‘eg:__count, __metadata , __references ‘ There is only one __count per Collection. Contentusing Can only be used on properties. Any suggestions ?
It possible by extending the simplemodule or by extending com.fasterxml.jackson.databind.Module. I have taken the second approach. Below are the summary of changes
added method to take JavaType as parameter.
Above method adds the new serilaizer to
The class ‘TypedSerializers extends Serializers.Base’ stores all the typed serializers in a HashMap.
Changed the logic of findSerializer method in TypedSerializers
Below change is needed when registering a customserializer
The resulting behaviour is, when ‘List of type Product’ is passed to ObjectMapper , it tries to locate a suitable serilaizer. We are maintaining the generic serializers in the map of _javaTypeMappings. The Objecmapper executes findSerializer. The findSerializer first checks for an avaliable serializer in _javaTypeMappings. In this case it returns prodctlistserializer. When ‘List of type Client ‘ is passed it returns clientlistserializer.
I have taken all source code under com.fasterxml.jackson.databind.Module to a package in my project and added above changes.