Spring Boot 中注解方式 对接口中Bigdecimal字段属进行小数保留序列化

      最近有做涉及到echarts图标有关的数据的处理,其中包含了很多数字类型的数据的处理,其中涉及到了数字小数点的保留的问题,如何全局的把控或者个性化的处理,结合咨询AI,最终选择通过注解和自定义序列化器的方式来进行实现。

        面向保留小数的话,大概就是保留几位小数(例如默认一位),以及保留小数 的方式(例如默认四舍五入),以及该注解是否默认是开启的(例如默认true)

1. 自定义注解

        也可以在增加一个自定义注解在作用类上,默认对该;类所有Bigdecimal字段起作用。

import java.lang.annotation.*;


//目标作用在字段上
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface EnableDecimalRounding {
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RoundDecimal {

    //默认true
    boolean enable() default true;
    //默认保留一位
    int scale() default 1;
    //默认四四舍五入
    RoundingMode roundingMode() default RoundingMode.HALF_UP;
}

        

2. 自定义序列化器

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalRoundingSerializer extends JsonSerializer<BigDecimal> {

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
         if (value == null) {
            gen.writeNull();
            return;
        }

        //如果字段维度 挨个配置太麻烦 可以在新增一个注解 在类上 如果类上有注解 直接 默认开启,
        //如果字段上也有 字段上优先级>类上
        //gen.getCurrentValue().getClass().isAnnotation......
        

        try {
            //注解有并且开启的话 进行格式化
            Field field = gen.getCurrentValue().getClass().getDeclaredField(gen.getOutputContext().getCurrentName());

            if (field.isAnnotationPresent(RoundDecimal.class)) {
                RoundDecimal annotation = field.getAnnotation(RoundDecimal.class);
                if (annotation.enabled()) {
                    value = value.setScale(annotation.scale(), annotation.roundingMode());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        gen.writeNumber(value);
    }
}

  配置类中 注册一下自定义序列化器

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.math.BigDecimal;

@Configuration
public class JacksonConfig {
    
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addSerializer(BigDecimal.class, new BigDecimalRoundingSerializer());
        mapper.registerModule(module);
        return mapper;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值