• [AIGC] 自定义Spring Boot中BigDecimal的序列化方式


    在很多场景下,我们需要对BigDecimal类型的数据进行特殊处理,比如保留三位小数。Spring Boot使用Jackson作为默认的JSON序列化工具,我们可以通过自定义Jackson的序列化器(Serializer)来实现,下面将详细介绍实现步骤。


    1. 创建一个自定义序列化类

    首先,我们需要创建一个自定义序列化器类,这个类需要继承com.fasterxml.jackson.databind.JsonSerializer这个类,并重写serialize方法。

    这个方法的作用就是告诉Jackson如何将Java对象转换为JSON。

    创建一个类,我们可以将其命名为CustomBigDecimalSerialize, 修改如下:

    import com.fasterxml.jackson.core.JsonGenerator;
    import com.fasterxml.jackson.databind.JsonSerializer;
    import com.fasterxml.jackson.databind.SerializerProvider;
    import java.io.IOException;
    import java.math.BigDecimal;
    
    public class CustomBigDecimalSerializer extends JsonSerializer<BigDecimal> {
        @Override
        public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if (value != null) {
                // 将BigDecimal保留3位小数,注意需要四舍五入
                BigDecimal decimal = value.setScale(3, BigDecimal.ROUND_HALF_UP);
                gen.writeNumber(decimal);
            }
        }
    }
    

    上述代码中,gen.writeNumber(decimal)就是将处理后的数据写入JSON中。

    2. 在需要的字段上使用注解

    我们需要在对应的BigDecimal字段上使用@JsonIgnore注解,来告诉Jackson使用这个新的序列化器,代码如下:

    import com.fasterxml.jackson.databind.annotation.JsonSerialize;
    
    public class ExampleEntity {
        @JsonSerialize(using = CustomBigDecimalSerializer.class)
        private BigDecimal number;
        // getters and setters...
    }
    

    这样一来,每当Jackson试图将这个类实例化为JSON时,它就会使用我们刚刚创建的CustomBigDecimalSerializer进行处理。

    3. 测试

    我们可以通过一个简单的Controller来进行测试:

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import javax.servlet.http.HttpServletResponse;
    import java.math.BigDecimal;
    
    @RestController
    @RequestMapping("/api")
    public class TestController {
        @GetMapping("/test")
        public ExampleEntity test() {
            ExampleEntity exampleEntity = new ExampleEntity();
            exampleEntity.setNumber(new BigDecimal("123.45678"));
            return exampleEntity;
        }
    }
    

    运行项目,访问"http://localhost:8080/api/test",可以看见返回的json串中BigDecimal类型的number字段已经被处理为保留3位小数的格式。

    以上就是自定义Spring Boot中BigDecimal的序列化方式的完整过程,通过自定义的序列化器,我们可以灵活地控制序列化的过程,满足各种各样的需求。


    全局生效的配置方式

    确实,您可以通过自定义Jackson ObjectMapperModule,将此序列化器全局应用到所有的BigDecimal字段。

    以下是实现步骤:

    1. 创建一个配置类
    @Configuration
    public class JacksonConfig {
    }
    
    1. 在配置类中,定义并配置一个ObjectMapper Bean:
    @Bean
    public ObjectMapper objectMapper(){
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(BigDecimal.class, new CustomBigDecimalSerializer());
        mapper.registerModule(module);
        return mapper;
    }
    

    SimpleModule是Jackson中的一个功能,它可以让我们将自定义的序列化器加入到ObjectMapper中。如上,我们创建了一个新的SimpleModule,然后通过 addSerializer 方法添加了我们自定义的BigDecimal序列化器,最后将这个模块注册到ObjectMapper中。

    这样,Jackson在序列化BigDecimal字段时,将全局使用我们自定义的序列化器。

    需要注意的是,@Bean注解的ObjectMapper将覆盖Spring Boot的默认ObjectMapper,这意味着所有Jackson的自动配置都将失效,您需要自行配置,或者使用Jackson2ObjectMapperBuilder来保留Spring Boot的自动配置:

    @Bean
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder){
        ObjectMapper mapper = builder.createXmlMapper(false).build();
        SimpleModule module = new SimpleModule();
        module.addSerializer(BigDecimal.class, new CustomBigDecimalSerializer());
        mapper.registerModule(module);
        return mapper;
    }
    

    以上,就是如何将自定义的BigDecimal序列化器全局配置到Spring Boot项目中的所有BigDecimal字段。

  • 相关阅读:
    IDEA通过原型(骨架)创建MavenJavaWeb项目
    力扣练习——33 原子的数量
    langchain介绍之-Prompt
    华为---PPP协议简介及示例配置
    论文阅读 - Coordinated Behavior on Social Media in 2019 UK General Election
    分享一下蛋糕店在微信小程序上可以实现什么功能
    717. 简单斐波那契
    Java毕业设计 SpringBoot 美食推荐系统 美食分享系统
    SQLite 日期 & 时间
    html5 图像标签
  • 原文地址:https://blog.csdn.net/qq_45704048/article/details/139455058