Pako Pako - 3 years ago 115
Java Question

Jackson Serializer Register SimpleModule with Generics

I have this class

public class ResultList<T> {......}


and my
JsonSerializer
class

public class ListProductSerializer extends JsonSerializer<ResultList<Product>> {..}


How do register the SimpleModule in the
ObjectMapper


this not work

MAPPER.registerModule(new SimpleModule()
.addSerializer(ResultList.class, new ListProductSerializer()));


i get this error

Error:(67, 17) java: method addSerializer in class com.fasterxml.jackson.databind.module.SimpleModule cannot be applied to given types;
required: java.lang.Class<? extends T>,com.fasterxml.jackson.databind.JsonSerializer<T>
found: java.lang.Class<com.onkalo.rest.json.wrapper.ResultList>,com.onkalo.rest.json.serializer.ListProductSerializer
reason: cannot infer type-variable(s) T
(argument mismatch; java.lang.Class<com.onkalo.rest.json.wrapper.ResultList> cannot be converted to java.lang.Class<? extends com.onkalo.rest.json.wrapper.ResultList<com.onkalo.service.domain.Product>>)

Answer Source

A way to resolve this is to use StdSerializer instead of its base class JsonSerializer, with the same serialize method you currently use and a constructor taking a JavaType e.g:

class ListProductSerializer extends StdSerializer<ResultList<Product>> {
    ListProductSerializer(JavaType type) {
        super(type);
    }

    @Override
    public void serialize( // your serialize method
}

This would be an appropriate JavaType in your case:

CollectionLikeType type = MAPPER.getTypeFactory()
        .constructCollectionLikeType(ResultList.class, Product.class);

Note how class types for both ResultList and Product are passed as separate arguments to constructCollectionLikeType. Also note that CollectionLikeType doesn't require that ResultList implements Collection.

And finally register the SimpleModule:

mapper.registerModule(new SimpleModule()
        .addSerializer(new ListProductSerializer(type)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download