SpringBoot使用fastjson的JsonField注解序列化Bigdecimal

2023-05-16

代码

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>xyz.qiuyiping</groupId>
    <artifactId>fastjson-bigdecimal-serialize</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>fastjson-bigdecimal-serialize</name>
    <description>Spring Boot使用fastjson的JsonField注解序列化Bigdecimal</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.56</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
package xyz.qiuyiping.fastjson_bigdecimal_serialize.config;

import com.alibaba.fastjson.serializer.*;

import java.text.DecimalFormat;

public class CustomerBigDecimalCodec extends BigDecimalCodec implements ContextObjectSerializer {

    public final static CustomerBigDecimalCodec instance = new CustomerBigDecimalCodec();

    /**
     * 当BigDecimal类型的属性上有@JsonFiled注解,且该注解中的format有值时,使用该方法进行序列化,否则使用fastjson的
     * BigDecimalCodec中的write方法进行序列化
     */
    @Override
    public void write(JSONSerializer serializer, Object object, BeanContext context){
        SerializeWriter out = serializer.out;
        if(object == null) {
            out.writeString("");
            return;
        }
        String format = context.getFormat();
        DecimalFormat decimalFormat = new DecimalFormat(format);
        out.writeString(decimalFormat.format(object));
    }

}
package xyz.qiuyiping.fastjson_bigdecimal_serialize.config;

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class HttpMessageConvertersConfig {

    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        //1.需要定义一个Convert转换消息的对象
        FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter();
        //2.添加fastjson的配置信息,比如是否要格式化返回的json数据
        FastJsonConfig fastJsonConfig=new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.DisableCircularReferenceDetect);
        //BigDecimal数据处理
        SerializeConfig serializeConfig = SerializeConfig.getGlobalInstance();
        serializeConfig.put(BigDecimal.class, CustomerBigDecimalCodec.instance);
        fastJsonConfig.setSerializeConfig(serializeConfig);
        //3.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        //4.中文乱码
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);

        return new HttpMessageConverters(fastConverter);

    }

}
package xyz.qiuyiping.fastjson_bigdecimal_serialize.entity;

import com.alibaba.fastjson.annotation.JSONField;

import java.math.BigDecimal;

public class MoneyEntity {

    private BigDecimal noFormatMoney;

    @JSONField(format = "¥#0.00")
    private BigDecimal formatMoney;

    private String currencyType;

    public BigDecimal getNoFormatMoney() {
        return noFormatMoney;
    }

    public void setNoFormatMoney(BigDecimal noFormatMoney) {
        this.noFormatMoney = noFormatMoney;
    }

    public BigDecimal getFormatMoney() {
        return formatMoney;
    }

    public void setFormatMoney(BigDecimal formatMoney) {
        this.formatMoney = formatMoney;
    }

    public String getCurrencyType() {
        return currencyType;
    }

    public void setCurrencyType(String currencyType) {
        this.currencyType = currencyType;
    }
}
package xyz.qiuyiping.fastjson_bigdecimal_serialize.web;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.qiuyiping.fastjson_bigdecimal_serialize.entity.MoneyEntity;

import java.math.BigDecimal;

@RestController
public class MoneyController {

    @GetMapping("/money")
    public Object money() {
        MoneyEntity moneyEntity = new MoneyEntity();
        moneyEntity.setNoFormatMoney(new BigDecimal(123.45));
        moneyEntity.setFormatMoney(new BigDecimal(67.89));
        moneyEntity.setCurrencyType("人民币");
        return moneyEntity;
    }

}

验证
启动springboot项目,访问http://localhost:8080/money
结果

{
    "currencyType":"人民币",
    "formatMoney":"¥67.89",
    "noFormatMoney":123.4500000000000028421709430404007434844970703125
}

github代码地址:https://github.com/cainiaoqiu/fastjson-bigdecimal-serialize

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot使用fastjson的JsonField注解序列化Bigdecimal 的相关文章

随机推荐

  • netty 堆外内存泄露排查盛宴

    这篇文章对于排查使用了 netty 引发的堆外内存泄露问题 xff0c 有一定的通用性 xff0c 希望对你有所启发 背景 最近在做一个基于 websocket 的长连中间件 xff0c 服务端使用实现了 socket io 协议 xff0
  • 线程池工具类的封装

    了解更多学习 ThreadPoolExecutor类 ThreadPool java package com tool me thread import java util Hashtable import java util Map im
  • 【性能测试】利用IxChariot测试路由器吞吐量(wan to lan & lan to wan)

    写在前面 因项目原因 xff0c 本人对路由器吞吐量测试进行了学习探索 在学习过程中 xff0c 了解到IxChariot这一工具 xff0c 而在实践中 xff0c 也遇到一些问题 xff0c 花了较多时间去尝试和摸索 在此本人将这次实践
  • 通用文本标注工具 labelme

    欢迎大家前往腾讯云社区 xff0c 获取更多腾讯海量技术实践干货哦 作者 xff1a 理查德 导语 一个支持文本类目标注和关键词打分的通用标注工具 xff0c 为文本分类模型和关键词抽取任务提供训练和测试数据 by 慕福楠 amp 孙振龙
  • 干货|基于CPU的深度学习推理部署优化实践

    背景介绍 随着人工智能技术在爱奇艺视频业务线的广泛应用 xff0c 深度学习算法在云端的部署对计算资源 xff0c 尤其是 GPU 资源的需求也在飞速增长 如何提高深度学习应用部署效率 xff0c 降低云平台运行成本 xff0c 帮助算法及
  • Keycloak授权服务指南

    为什么80 的码农都做不了架构师 xff1f gt gt gt 本文译自Keycloak官方文档 xff0c 原文链接 对应版本为5 0 概述 Keycloak支持细粒度的授权策略 xff0c 并可以对这些策略进一步组合 xff0c 如 x
  • postgresql的substr()函数

    为什么80 的码农都做不了架构师 xff1f gt gt gt code select substr 39 1234 39 0 3 as re code 如果是pg xff1a 得到的结果是12 如果是oracle xff1a 得到的结果是
  • 【docker】查看docker镜像的版本号TAG,从远程仓库拉取自己想要版本的镜像

    要想查看镜像的版本好TAG 需要在docker hub查看 地址如下 xff1a https hub docker com r library 进入之后 xff0c 在页面左上角搜索框搜索 xff0c 例如搜索redis 搜索完成如下 xf
  • Windows下慎用内核隔离

    1 开启内核隔离后只能通过注册表关闭 2 开启内核隔离后 默认会启动hybrid v 这个东西和虚拟机是冲突的 这样就用不了虚拟机了 3 解决方法 关闭内核隔离后 再关闭已经开启的hybrid v 基本参考下面 可能要重复几次才能有效的关闭
  • EntLib 3.1学习笔记(4) : Logging Application Block

    zh http www microsoft com china MSDN library enterprisedevelopment softwaredev dnpag2logging mspx mfr 61 true en http ms
  • linux开机启动

    linux 有自己一套完整的启动体系 xff0c 抓住了 linux启动的脉络 xff0c linux的启动过程将不再神秘 阅读之前建议先看一下附图 本文中假设inittab中设置的init tree为 xff1a etc rc d rc0
  • 设置TextBox控件readOnly="True",后台无法取得客户端TextBox中值的解决方法

    在TextBox中设置属性 ContentEditable 61 34 false 34 即可 例 xff1a lt asp TextBox Id 61 34 txt DeptName 34 runat 61 34 server 34 Te
  • matlab练习程序(双边滤波)

    双边滤波模板主要有两个模板生成 xff0c 第一个是高斯模板 xff0c 第二个是以灰度级的差值作为函数系数生成的模板 然后这两个模板点乘就得到了最终的双边滤波模板 第一个模板是全局模板 xff0c 所以只需要生成一次 第二个模板需要对每个
  • hive:导出数据记录中null被替换为\n的解决方案

    在hive中 xff0c 一般情况下通过 1 use my hive db 2 set hive merge mapfiles 61 true 3 set hive merge mapredfiles 61 true 4 set hive
  • STP试验的综合应用

    实验环境 xff1a Catalyst 2950 24 S1 SwA S2 SwB S3 SwC S4 SwD 实验目的 xff1a 1 利用VTP协议实现VLAN配置的一致性 2 通过PVST的配置实现交换网络的负载分担 其次实现冗余备份
  • Ubuntu12.04LTS安装好后是空白桌面的解决步骤

    安装完毕启动后 xff0c 明显慢的要死 xff0c 登陆后竟然是一个空白的桌面环境 xff0c Ctrl 43 Alt 43 T 根本没有任何反应 唯一的反应就是右键能够创建文件和文档 同时打开的窗口没有最大化 xff0c 最小化及关闭按
  • could not execute menu item系统找不到指定的文件

    Wamp3 0 6 64bit xff0c 系统任务栏图标 xff0c 左键 xff0c Apache菜单 xff0c httpd conf xff0c 报错 could not execute menu item 系统找不到指定的文件 根
  • 这么好用的U盘数据恢复软件,推荐!

    U盘受到了用户不同程度的青睐 xff0c 可以将临时要用的数据输入到U盘中 但是U盘在使用过程中 xff0c 也会出现一些突发情况 xff0c 让用户措手不及 xff0c 其中最常见的就属数据丢失 数据丢失的原因包括多种 xff0c 误删除
  • node+微信小程序实现商城案例

    说明 xff1a 1 本人也是初次完整使用小程序 xff0c 如有BUG或者不足的地方请在Issues或者本文下方留言 xff0c 作者会尽快修改 xff0c 谢谢 xff01 2 本项目适合初学者或者准备自学小程序的伙伴 小程序功能 xf
  • SpringBoot使用fastjson的JsonField注解序列化Bigdecimal

    代码 lt xml version 61 34 1 0 34 encoding 61 34 UTF 8 34 gt lt project xmlns 61 34 http maven apache org POM 4 0 0 34 xmln