简体   繁体   English

没有注释的自定义序列化

[英]Custom serialization without annotations

Is there a way on Springboot that I can implement a custom serializer for a specific field on my request without doing annotations? Springboot 上有没有一种方法可以在我的请求中为特定字段实现自定义序列化程序而无需进行注释?

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.如果我们可以创建一个 bean 或覆盖配置并序列化一个字符串输入(来自 json 请求),我更喜欢我的请求 pojo 上的 OffsetDateTime 字段。

I cannot annotate because my request classes are auto-generated..我无法注释,因为我的请求类是自动生成的..

You can register the serializer programatically in jackson.您可以在 jackson 中以编程方式注册序列化程序。 The class needing custom serialization:需要自定义序列化的 class :

public class SpecialObject {

    private String field;
    private String anotherField;

    //getters, setters
}

The wrapper class, where it is a field:包装器 class,它是一个字段:

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.现在您需要在一个Module中添加您的序列化程序,并在 object 映射器中注册该模块。 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM