springboot~重写json序列化方式

在springboot里,推荐我们通过WebMvcConfigurer的派生类重写你的请求,你可以利用WebMvcConfigurer对http请求添加一些拦截器,addCorsMappings,addResourceHandlers,消息返回格式等等,需要注意的是,你需要使用@EnableWebMvc注解override springboot默认的方法;WebMvcConfigurer虽然是接口,但它的方法都是有default默认实现的。

public interface WebMvcConfigurer {
    default void configurePathMatch(PathMatchConfigurer configurer) {
    }

    default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    }

    default void configureAsyncSupport(AsyncSupportConfigurer configurer) {
    }
...
}

我们来定义自己的WebMvcConfigurer,并且重写一个JSON输出的格式

@Configuration
@EnableWebMvc //覆盖默认的配置
public class WebMvcConfigurerImpl implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();

        /**
         * 序列换成Json时,将所有的Long变成String
         * 因为js中得数字类型不能包括所有的java Long值
         */
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);

        // 所有的double类型返回保留三位小数
        simpleModule.addSerializer(BigDecimal.class, new MoneySerialize());

        // double保留两位小数
        simpleModule.addSerializer(Double.class, new DoubleSerialize());
        simpleModule.addSerializer(Double.TYPE, new DoubleSerialize());

        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);
    }
/**
     * money serializer.
     */
    public class MoneySerialize extends JsonSerializer<Object> {
        //修改要除的数据
        final BigDecimal TEMP = BigDecimal.valueOf(1000000L);

        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if (value != null) {
                BigDecimal bigDecimal = new BigDecimal(value.toString());
                gen.writeNumber(bigDecimal.divide(TEMP, 4, RoundingMode.DOWN));
            }
        }
    }

    /**
     * double serializer.
     */
    public class DoubleSerialize extends JsonSerializer<Double> {

        private DecimalFormat df = new DecimalFormat("##.00");

        @Override
        public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException, JsonProcessingException {
            if (value != null) {
                gen.writeString(df.format(value));
            }
        }
    }

然后我们在返回对象之后,它的double,BigDecimal的属性将被格式化

{"name":"zzl","email":null,"sex":null,"total":"5.00","totalMoney":0.0001}
posted @   张占岭  阅读(2527)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
历史上的今天:
2017-07-13 DotNetCore跨平台~Dockerfile的解释
2012-07-13 基础才是重中之重~国外大牛对linq查询的扩展,有时还是T-SQL的样子好
2011-07-13 工作中的问题~按着枚举类型的字段进行排序
点击右上角即可分享
微信分享提示