zoukankan      html  css  js  c++  java
  • fastjson转换数字时,格式化小数点

    使用fastjson类库转换java对象时,对于BigDecimal类型,有时需要特殊格式,比如:

    1.0,转为json时候,要求显式为1,因此需要在转换时做处理。步骤如下:

    1、新建类,实现ValueFilter接口

    import java.math.BigDecimal;
    import com.alibaba.fastjson.serializer.ValueFilter;
     
    /**
     * 处理BigDecimal小数部分为0的情况
     * 123.5 -> 123.5
     * 12.0 -> 12
     * 12.00 -> 12
     */
    public class BigDecimalValueFilter implements ValueFilter {
        /**
         * @param object 对象
         * @param name 对象的字段的名称
         * @param value 对象的字段的值
         */
        @Override
        public Object process(Object object, String name, Object value) {
            if(null != value && value instanceof BigDecimal) {
                String str = value.toString();
                if(str.endsWith(".0")) {
                    str = str.substring(0, str.length()-2);
                } else if(str.endsWith(".00")) {
                    str = str.substring(0, str.length()-3);
                } else {
                    str = value.toString();
                }
                return str;
            }
            return value;
        }
    }

    2、对象转为json时,第二个参数填入该类即可。

    BigDecimalValueFilter filter = new BigDecimalValueFilter();
    String contentJson = JSON.toJSONString(request, filter);
  • 相关阅读:
    Linux
    python中元类
    POJ 1182 食物链
    POJ 1733 Parity game
    top 介绍
    周记 2014.8.31
    windows10配置python
    oracle执行update时卡死问题的解决办法
    An Easy Introduction to CUDA C and C++
    super()
  • 原文地址:https://www.cnblogs.com/edda/p/14588149.html
Copyright © 2011-2022 走看看