'Using a custom serializer with ObjectMapper

I have a need for two mappers in the application. One that maps all fields in all DTOs and another that skips on a few fields that contain some PII.

I created a custom Serializer:

public class PIIMaskerSerializer extends StdSerializer {
    public PIIMaskerSerializer() {
        this(null);
    }

    public PIIMaskerSerializer(Class t) {
        super(t);
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        try {
            for (final Field f : value.getClass().getFields()) {
                if (!f.isAnnotationPresent(PIIField.class)) {
                    gen.writeStringField(f.getName(), (String) f.get(value));
                }
            }
        } catch (final Exception e) {
            //
        }
        gen.writeEndObject();
    }
}```

Using this serializer in custom module:

public PIIMaskerModule() {
        addSerializer(new PIIMaskerSerializer());
    }

and then created a object mapper with this module ;

However I am getting this error:

JsonSerializer of type PIIMaskerSerializer does not define valid handledType() -- must either register with method that takes type argument or make serializer extend 'com.fasterxml.jackson.databind.ser.std.StdSerializer'

Also, I am not creating a custom serializer for only one type of objects, but for any/all objects like out of the box objectmapper.

Really appreciate the help.



Solution 1:[1]

Alright, I figured this out with trial and error. There was a problem with the SimpleModule.

Changing the constructor from

public PIIMaskerModule() {
        addSerializer(new PIIMaskerSerializer());
    }

to

public PIIMaskerModule() {
        addSerializer(Object.class, new PIIMaskerSerializer());
    }

fixed it for me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akash