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());
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With