自定义Moshi BigDecimal JsonAdapter.Factory适配器工厂

背景

所在公司项目中,涉及金额数字,所以在反序列化数字金额时,选择了BigDecimal作为金额相关JSON字段的对象类型。在项目中使用Kotlin语言,搭配Retrofit框架和Moshi作为序列化工具,但Moshi在使用当中发现,是不支持string、number类型的JSON字段转换成BigDecimal类型的参数的。于是需要自定义一个JsonAdapter.Factory来解决这一问题。

先来介绍为什么选BigDecimal

1. 精确的十进制表示

BigDecimal内部,通过整数+小数位存储数据,无精度损失,例如 321.45 存储为 32145 X 10^-2。

2. 完全控制舍入行为

提供多种舍入模式,如RoundingModel.HALF_UP 四舍五入,符合财务规范。

3. 支持任意精度

不受固定自己安长度限制,可处理超大金额或超高精度

4. 避免隐式转换风险

强制使用显示计算方式 如,add()mulitply() ,避免意外错误。

代码如下

kotlin 复制代码
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import java.lang.reflect.Type
import java.math.BigDecimal

class BigDecimalAdapterFactory : JsonAdapter.Factory {
    override fun create(type: Type, annotations: Set<Annotation?>, moshi: Moshi): JsonAdapter<*>? {
        if (type != BigDecimal::class.java) return null

        return object : JsonAdapter<BigDecimal>() {
            override fun fromJson(reader: JsonReader): BigDecimal? {
                return when (reader.peek()) {
                    JsonReader.Token.NUMBER -> {
                        val number = reader.nextDouble()
                        BigDecimal.valueOf(number)
                    }
                    
                    JsonReader.Token.STRING -> {
                        val string = reader.nextString()
                        BigDecimal(string)
                    }

                    JsonReader.Token.NULL -> {
                        null
                    }

                    else -> {
                        val intValue = reader.nextInt()
                        BigDecimal(intValue)
                    }
                }
            }

            override fun toJson(wirtter: JsonWriter, value: BigDecimal?) {
                if (value != null) {
                    wirtter.value(value)
                } else {
                    wirtter.nullValue()
                }
            }
        }.nullSafe()
    }
}
相关推荐
万少3 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站5 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名8 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
NineData8 小时前
数据库迁移总踩坑?用 NineData 迁移评估,提前识别所有兼容性风险
数据库·程序员·云计算
王晓枫8 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊8 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter8 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折8 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_9 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial9 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js