Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson register custom json serializer

This is my custom JSON Serializer and I'm trying to register it as a module. Here is what I have so far.

public class MaptoListSerializer extends JsonSerializer<Map<String, Car<?, ?>>> {

        @Override
        public void serialize(Map<String, Car<?, ?>> value, JsonGenerator gen, SerializerProvider serializers)throws IOException, JsonProcessingException {
             gen.writeObject(value.values());
        }
}

Here is my module class that I created (Can't seem to add serializer).

public class CustomModule extends SimpleModule {

private static final long serialVersionUID = -9105685985325373621L;

public CustomModule() {
    super("CustomModule");
}

@Override
public void setupModule(SetupContext context) {
    SimpleSerializers serializers = new SimpleSerializers();

    //THIS DOESN'T WORK . HOW DO I ADD THE SERIALIZER?
    serializers.addSerializer(HashMap.class, new MaptoListSerializer ());

    context.addSerializers(serializers);
 }
}

Here is how Object mapper it used (This works)

mapper = new ObjectMapper();
mapper.registerModule(new CustomModule());
like image 535
user3100209 Avatar asked Sep 17 '25 12:09

user3100209


1 Answers

This is an issue due to using HashMap, a raw type while this case requires generics. You can solve this by basing you custom serializer on StdSerializer as recommended in the docs. Keep the serialize method as it is, but define serializer with a constructor like this:

class MaptoListSerializer extends StdSerializer<Map<String, Car<?, ?>>> {
    MaptoListSerializer(JavaType type) {
        super(type);
    }

Then to the important bit where you create an appropriate JavaType and pass it to this constructor:

MapType type = context.getTypeFactory()
    .constructMapType(HashMap.class, String.class, Car.class);
serializers.addSerializer(new MaptoListSerializer(type));

context.addSerializers(serializers);
like image 50
Manos Nikolaidis Avatar answered Sep 20 '25 07:09

Manos Nikolaidis