You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Spring Boot中如何让BigDecimal保留小数末尾零且以数值形式返回

解决Spring Boot中BigDecimal返回无引号且保留小数末尾零的问题

方案一:字段级自定义Jackson序列化器

针对单个字段精准控制序列化规则:

  1. 编写自定义BigDecimal序列化类,强制保留两位小数并以数值类型输出:
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;
import java.text.DecimalFormat;

public class CustomBigDecimalSerializer extends JsonSerializer<BigDecimal> {
    // 固定格式:保留两位小数,不足补零
    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00");

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null) {
            // 以数值类型写入,而非字符串
            gen.writeNumber(DECIMAL_FORMAT.format(value));
        } else {
            gen.writeNull();
        }
    }
}
  1. 在实体类目标字段上添加注解指定序列化器:
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.math.BigDecimal;

public class Transaction {
    // 其他字段...
    
    @JsonSerialize(using = CustomBigDecimalSerializer.class)
    private BigDecimal amount;

    // getter、setter方法
}

方案二:全局Jackson配置(批量生效)

如果需要所有BigDecimal字段统一遵循该规则,可通过全局配置实现:

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

@Configuration
public class JacksonGlobalConfig {
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule bigDecimalModule = new SimpleModule();
        // 注册自定义序列化器
        bigDecimalModule.addSerializer(BigDecimal.class, new CustomBigDecimalSerializer());
        objectMapper.registerModule(bigDecimalModule);
        
        // 禁止BigDecimal以科学计数法输出
        objectMapper.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, true);
        return objectMapper;
    }
}

以上两种方案均可实现"amount":10000.00的预期效果——既保留小数末尾的零,又以无引号的数值类型输出,规避了@JsonFormat(shape=STRING)带来的字符串格式问题。

内容的提问来源于stack exchange,提问作者Durga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 16:27:26