美文网首页Kotlinkotlin程序员
68. (android开发) Gson的坑之关于CreatTi

68. (android开发) Gson的坑之关于CreatTi

作者: 厚土火焱 | 来源:发表于2018-05-01 21:24 被阅读35次

    每一个使用 Kotlin 的在进行服务端访问的时候,json 解析免不了要使用
    Gson,今天偶尔发现了一个奇怪的 CreatTime 坑。在坑里待了 3 天,终于出坑了。
    首先比较一下下面两段代码的差别
    代码一:

    for (i in 0..jsonObject.length() - 1){
                        val managerInfo = jsonObject.getJSONObject(i).toString()
                        val mmtemp = Gson().fromJson(managerInfo, ManagerPower::class.java)
                        try {
                            dataList.add(ManagerPower(mmtemp.Id, mmtemp.PowerCode, mmtemp.PowerName, mmtemp.PowerInfo, mmtemp.OrderNum, mmtemp.PowerGroupCode, mmtemp.CreateTime, mmtemp.Creator, mmtemp.UpdateTime, mmtemp.Updator))
                            Log.d("joel test --> ", mmtemp.CreateTime)
                        }catch (e : Exception){
                            Log.d("joel error --> ", "ManagerPowerEditActivity.kt line 98 \r\n"+e.toString() + "\r\n mmtemp.CreatTime is " + mmtemp +"\r\n" + managerInfo.toString())
                        }
                    }
    

    代码二:

    for (i in 0..jsonObject.length() - 1){
                        val managerInfo = jsonObject.getJSONObject(i).toString()
                        val mmtemp = Gson().fromJson(managerInfo, ManagerPower::class.java)
                        try {
                            dataList.add(ManagerPower(mmtemp.Id, mmtemp.PowerCode, mmtemp.PowerName, mmtemp.PowerInfo, mmtemp.OrderNum, mmtemp.PowerGroupCode, mmtemp.CreateTime, mmtemp.Creator, mmtemp.UpdateTime, mmtemp.Updator))
                            Log.d("joel test --> ", mmtemp.CreateTime)
                        }catch (e : Exception){
                            Log.d("joel error --> ", "ManagerPowerEditActivity.kt line 98 \r\n"+e.toString() + "\r\n mmtemp.CreateTime is " + mmtemp +"\r\n" + managerInfo.toString())
                        }
                    }
    

    这两段代码的差别,只在 mmtemp.CreateTime 和 mmtemp.CreatTime 上,其他的一模一样。一个可以正常运行解析 json ,一个不可以运行。
    mmtemp.CreatTime 字段的值在 fromJson 时会给出 null 值。

    相关文章

      网友评论

      • 小武说:土哥,这句`val mmtemp = Gson().fromJson(managerInfo, ManagerPower::class.java)`是否需要json和类定义字段匹配才能解析?
        厚土火焱:@小武说 managerInfo, ManagerPower::class.java 这两个要结构相同才行

      本文标题:68. (android开发) Gson的坑之关于CreatTi

      本文链接:https://www.haomeiwen.com/subject/aqhfrftx.html