fastjson在kotlin不使用kotlin-reflect库怎么使用?

原文地址:https://blog.raoyunsoft.com/post/23

现象

我在Android上使用fastjson解析kotlin类的时候出现报错

val model = JSON.parseObject(json, InvitationHistoryModel::class.java)

报错default constructor not found

java 复制代码
default constructor not found .InvitationHistoryModel
com.alibaba.fastjson.JSONException: default constructor not found .InvitationHistoryModel
at app//com.alibaba.fastjson.parser.JavaBeanInfo.build(JavaBeanInfo.java:502)
at app//com.alibaba.fastjson.parser.JavaBeanDeserializer.<init>(JavaBeanDeserializer.java:37)
at app//com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:363)

我的写法

kotlin 复制代码
@Keep
data class InvitationHistoryModel(
    @JSONField(name = "creditsEarned")
    val creditsEarned: Int = 0,
    
    @JSONField(name = "invitations")
    val invitations: Int = 0,
    
    @JSONField(name = "history")
    val history: List<InvitationHistoryRecord> = emptyList()
) {
    /**
     * 检查是否有邀请记录
     * @return true表示有邀请记录,false表示没有
     */
    fun hasInvitations(): Boolean {
        return history.isNotEmpty()
    }
}

但是我反编译之后是有默认构造函数的,奇怪

不好的解决方案

找了一圈资料发现需要添加kotlin反射依赖

implementation("org.jetbrains.kotlin:kotlin-reflect:1.9.25")

但是这个库的jar有3.3M 实际APK会增加0.7M,这...包大小过不了啊,会被喷死

最终解决方案:

添加@JSONCreator constructor,并且把参数由val改成var可解决,还要注意加@Keep注解防止被混淆

如下:

kotlin 复制代码
@Keep
data class InvitationHistoryModel @JSONCreator constructor(
    @JSONField(name = "creditsEarned")
    var creditsEarned: Int = 0,

    @JSONField(name = "invitations")
    var invitations: Int = 0,

    @JSONField(name = "history")
    var history: List<InvitationHistoryRecord> = emptyList()
) {

    /**
     * 检查是否有邀请记录
     * @return true表示有邀请记录,false表示没有
     */
    fun hasInvitations(): Boolean {
        return history.isNotEmpty()
    }
}
相关推荐
二流小码农30 分钟前
鸿蒙开发:上传一张参考图片便可实现页面功能
android·ios·harmonyos
鹏程十八少1 小时前
4.Android 30分钟手写一个简单版shadow, 从零理解shadow插件化零反射插件化原理
android·前端·面试
Kapaseker1 小时前
一杯美式搞定 Kotlin 空安全
android·kotlin
三少爷的鞋2 小时前
Android 协程时代,Handler 应该退休了吗?
android
火柴就是我15 小时前
让我们实现一个更好看的内部阴影按钮
android·flutter
FunnySaltyFish19 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
砖厂小工1 天前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心1 天前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心1 天前
Android 17 来了!新特性介绍与适配建议
android·前端
Kapaseker1 天前
Compose 进阶—巧用 GraphicsLayer
android·kotlin