您现在的位置是:首页 > 文章详情

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

日期:2019-03-23点击:782

代码

<?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

原文链接:https://yq.aliyun.com/articles/695036
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章