0

Is there a way on Springboot that I can implement a custom serializer for a specific field on my request without doing annotations?

I prefer if we could create a bean or a override a configuration and serialize a string input (from json request) going to OffsetDateTime field on my request pojo.

I cannot annotate because my request classes are auto-generated..

Rye
  • 33
  • 5

1 Answers1

1

You can register the serializer programatically in jackson. The class needing custom serialization:

public class SpecialObject {

    private String field;
    private String anotherField;

    //getters, setters
}

The wrapper class, where it is a field:

public class WrapperObject {

    private String text;
    private SpecialObject specialObject;

    //getters, setters
}

The serializer:

public class SpecialObjectSerializer extends StdSerializer<SpecialObject> {

    public SpecialObjectSerializer() {
        super(SpecialObject.class);
    }

    @Override
    public void serialize(SpecialObject value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("fieldChanged", value.getField());
        gen.writeStringField("anotherFieldChanged", value.getAnotherField());
        gen.writeEndObject();
    }
}

Nothing fancy, just changing field names when serializing.

Now you need to add your serializer in a Module and register that module in object mapper. You can do it like this:

public class NoAnnot {

    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        //add serializer in module
        module.addSerializer(SpecialObject.class, new SpecialObjectSerializer());
        //register module
        objectMapper.registerModule(module);
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        
        SpecialObject specialObject = new SpecialObject();
        specialObject.setField("foo");
        specialObject.setAnotherField("bar");
        WrapperObject wrapperObject = new WrapperObject();
        wrapperObject.setText("bla");
        wrapperObject.setSpecialObject(specialObject);
        String json = objectMapper.writeValueAsString(wrapperObject);
        System.out.println(json);
    }
}
Chaosfire
  • 4,818
  • 4
  • 8
  • 23