Android:使用Gson常见问题(包含解决将Long型转化为科学计数法的问题)

一、解决将Long型转化为科学计数法的问题

1.1 场景

将一个对象转为Map类型时,调用Gson.fromJson发现,原来对象中的long类型的personId字段,被解析成了科学计数法,导致请求接口失败,报参数错误。

解决结果图
在这里插入图片描述

1.2、ExampleUnitTest.kt示例代码
data class ReuestParmObj(val personId: Long = 1668394335647, val personType: Int = 1)
class ExampleUnitTest {
   
   
    private val mGson: Gson = Gson()

    @Test
    fun gsonReuestParmJson() {
   
   
        val reuestParmObj = ReuestParmObj(1668394335647, 1)
        val reuestParmJson: String = mGson.toJson(reuestParmObj)
        println("reuestParmJson信息:$reuestParmJson")
        val mapParm: Map<String, *> =
            mGson.fromJson(reuestParmJson, Map::class.java) as Map<String, *>
        println("mapParms信息:$mapParm")
    }
}

测试结果
在这里插入图片描述

1.3 解决将Long型转化为科学计数法问题的方案

修改gson配置
private val mGson: Gson = GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create()

data class ReuestParmObj(val personId: Long = 1668394335647, val personType: Int = 1)
class ExampleUnitTest {
   
   
//    private val mGson: Gson = Gson()
  private val mGson: Gson = GsonBuilder().setLongSerializationPolicy(LongSerializationPolicy.STRING).create()

    @Test
    fun gsonReuestParmJson() {
   
   
        val reuestParmObj = ReuestParmObj
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值