使用注解的方式实现jackson将json字符串转对象时格式化小数

新增注解

import com.dbl.util.DecimalFormatJsonDeserializer;
import com.fasterxml.jackson.annotation.JacksonAnnotationsInside;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@JacksonAnnotationsInside
@JsonDeserialize(using = DecimalFormatJsonDeserializer.class)
public @interface DecimalFormat {
    /*   * 小数点后保留的位数   */
    int scale() default 2;

    /**
     * 是否抛出异常,不抛出异常但是出现了异常的情况会返回默认值
     */
    boolean isThrowException() default true;

    /**
     * 默认值,值不是数字或空字符串的情况返回该值
     */
    double defaultVal() default 0.0;

    /**
     * 格式化的规则,默认四舍五入
     */
    RoundingMode roundMode() default RoundingMode.HALF_UP;
}

测试用实体类

import com.dbl.annotation.DecimalFormat;
import lombok.Data;

@Data
public class Bill {
    @DecimalFormat(scale = 2)
    private Double money;
}

序列化转换类

import com.dbl.annotation.DecimalFormat;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DecimalFormatJsonDeserializer extends JsonDeserializer<Object> {
    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        // 默认是要抛出异常的
        boolean isthrowException = true;
        double defaultVal = 0.0;
        // 当前转换的字段的类型
        Class<?> type = null;
        // 转换过程中是否抛出了异常,如果出现异常并且没有抛出异常的情况需要返回默认值
        boolean isException = false;
        try {
            String numStr = jsonParser.getText();
            Class<?> clazz = jsonParser.getCurrentValue().getClass();
            Field field = clazz.getDeclaredField(jsonParser.getCurrentName());
            // 加了注解才会进入到这个方法,这里就不再校验注解为null的情况
            DecimalFormat annotation = field.getAnnotation(DecimalFormat.class);
            // 保留的小数位数
            int scale = annotation.scale();
            // 是否抛出异常
            isthrowException = annotation.isThrowException();
            // 默认值
            defaultVal = annotation.defaultVal();
            // 格式化的规则,默认是四舍五入
            RoundingMode roundingMode = annotation.roundMode();
            roundingMode = roundingMode == null ? RoundingMode.HALF_UP : roundingMode;
            // 需要转换的字段类型
            type = field.getType();
            // 空字符串和非数字字符
            if (StringUtils.isEmpty(numStr) || !isNumeric(numStr)) {
                if (type == String.class) {
                    return String.valueOf(defaultVal);
                } else {
                    return defaultVal;
                }
            }
            BigDecimal decimalValue = new BigDecimal(numStr);
            if (type == String.class) {
                return decimalValue.setScale(scale, roundingMode).toString();
            } else {
                return decimalValue.setScale(scale, roundingMode).doubleValue();
            }
        } catch (Exception e) {
            log.error("数字格式转换异常:", e);
            if (isthrowException) {
                isException = true;
                throw e;
            } else {
                if (type == String.class) {
                    return String.valueOf(defaultVal);
                } else {
                    return defaultVal;
                }
            }
        }
    }

    public boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
}

测试

import com.dbl.entity.Bill;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;


@RestController
public class Test {
    @GetMapping
    public Bill test(String money) throws IOException {
        String json = "{\"money\":" + money + "}";
        ObjectMapper mapper = new ObjectMapper();
        Bill b = mapper.readValue(json, Bill.class);
        System.out.println(b.getMoney());
        return b;
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值