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

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


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

首先,我们需要创建一个自定义序列化器类,这个类需要继承com.fasterxml.jackson.databind.JsonSerializer<T>这个类,并重写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字段。

  • 26
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Spring Boot,`BigDecimal` 类型用于处理精确的浮点数和货币计算,特别适合处理非整数的金融交易的数值,因为它可以避免舍入误差。然而,`BigDecimal` 对于非终止小数(即无限循环小数)和无法精确表示的小数可能会抛出异常。 Non-terminating decimal expansion, or "no exact representable decimal result" 表示的是由于数学上的限制,有些十进制数在二进制系统是无法精确表示为有限位的,比如 0.1(等于 1/10),在二进制就表现为无限循环的小数。在使用 `BigDecimal` 时,如果试图将这样一个无限小数转换为 `BigDecimal` 或执行涉及精确比较的操作,可能会遇到 `ArithmeticException`,提示 "MathContext does not permit conversion from inexact result". 例如,如果你尝试这样操作: ```java BigDecimal oneThird = new BigDecimal("0.1"); ``` 实际上,这将创建一个无限循环小数。当你尝试进一步操作这个 `oneThird`,如加减乘除时,可能会因为无法得到精确结果而引发异常。 解决这类问题的方法通常是在进行计算时,明确指定 `MathContext`(数学上下文),它可以控制精度和舍入策略。例如: ```java MathContext mc = new MathContext(10, RoundingMode.HALF_UP); BigDecimal oneThird = new BigDecimal("0.1").setScale(10, mc); ``` 这里设置了10位小数的精度,并且使用了向上舍入(`RoundingMode.HALF_UP`)。这样就可以在保持可读性的前提下,处理这类非精确但常见的数值操作。相关问题如下:
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员三木

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值