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()
    }
}
相关推荐
Bruce_Liuxiaowei2 小时前
Python 实例赋值遮蔽类属性:一个从不报错的静默陷阱
开发语言·python·语法糖
BoomHe3 小时前
Android Framework 文件应用移植到 AndroidStudio
android
aramae4 小时前
MySQL内置函数(7)
开发语言·笔记·后端·mysql·其他
传奇开心果编程4 小时前
【Jetpack Compose基础语法学与练】第8课 rememberSaveable,页面旋转/系统重建保留状态
android·学习·ui·kotlin·android jetpack
>Andre<4 小时前
UFS5.0标准中文全译·卷一:范围、术语与架构
android·linux·嵌入式硬件
事圆则缓5 小时前
Java 8 Lambda、Stream、Optional 与 Android 边界:从回调语法到运行时兼容
android·java
mmsx5 小时前
Android 地图十万要素不卡顿:空间网格 + 渐进式加载的移动端实践
android·大数据·opengl
码行山野赴时序归途7 小时前
链表家族收官篇:循环链表
c语言·开发语言·数据结构·链表
景熙55237 小时前
单体项目编写思路和落地形式
java·开发语言
Godikov7 小时前
Android 工业终端保活实战:前台服务 + 开机自启 + 更新自启的三重保障
android