简体   繁体   English

Java Jackson 总是将一个类型序列化为另一个类型

[英]Java Jackson Always Serialize One Type As Another

Is there a way to tell Jackson to always serialize one type to another.有没有办法告诉 Jackson 始终将一种类型序列化为另一种类型。 In my case I would like to always serialize Long to String.就我而言,我想始终将 Long 序列化为 String。 Right now whenever there is an object with a Long property we have to annotate it with @JsonSerialize(using=ToStringSerializer.class) .现在,只要有一个带有 Long 属性的 object,我们就必须用@JsonSerialize(using=ToStringSerializer.class)对其进行注释。 This is tedious and easy to forget.这是乏味且容易忘记的。

I would like to be able to configure the Jackson object mapper to always convert Long to String in the spring boot bean creation.我希望能够配置 Jackson object 映射器以始终在 spring 引导 bean 创建中将 Long 转换为 String。

IMHO, multiple options are there.恕我直言,有多种选择。

I

com.fasterxml.jackson.databind.ser.std.StdSerializer implementation that can be set to your ObjectMapper in the spring context. com.fasterxml.jackson.databind.ser.std.StdSerializer 实现,可以在 Z2A2D595E6ED9A0B24F027F2B63B134DZ 上下文中设置为您的 ObjectMapper。

    @Bean
    public Jackson2ObjectMapperBuilder objectMapperBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        ....
        builder.serializerByType(<type>, <your custom serializer>);
        return builder;
    }

As for the custom serializer, you can extend the above-mentioned class StdSerializer .至于自定义序列化器,您可以扩展上述 class StdSerializer

II

spring.jackson.generator.write-numbers-as-strings=true spring.jackson.generator.write-numbers-as-strings=true

Note笔记

Be aware of that Feature.WRITE_NUMBERS_AS_STRINGS has deprecated Since 2.10 of jackson version.请注意 Feature.WRITE_NUMBERS_AS_STRINGS 自 jackson 版本的 2.10 起已弃用。

I hope it helps.我希望它有所帮助。

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

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