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()
    }
}
相关推荐
恋猫de小郭29 分钟前
Android Keep Rules 解读,直接影响 Google Play 上架和曝光
android·前端·flutter
FlightYe40 分钟前
音视频修炼之容器与协议(六):HTTP 协议
android·linux·网络·网络协议·算法·http·音视频
小飞在努力1 小时前
【实现负载均匀在线判题④】接入 cpp-httplib 实现编译服务 HTTP 网络化
c语言·开发语言·c++·笔记·http
炸薯条!1 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
CappuccinoRose1 小时前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
tryCbest2 小时前
Python 爬虫从入门到实战(二):进阶篇——反爬对抗、并发与动态页面
开发语言·爬虫·python
S_WEAN3 小时前
【C++】STL - Priority_queue的使用及模拟实现与仿函数
开发语言·c++
星落梦生3 小时前
Tlias前端案例涉及知识点 (14)
开发语言·前端·javascript
FRing0314 小时前
vue2干货总结12(loading效果、全局前置导航守卫、搜索历史管理)
开发语言·前端·javascript·vue.js·vue2
wefg114 小时前
【项目】C++ 基于 Vibe Coding 的 OJ 平台
开发语言·c++