You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Kotlin Serialization解析JSON时遇意外Token错误,求解决方案

问题解决方法

错误原因

报错本质是传入decodeFromString的字符串格式不符合预期:Kotlin Serialization尝试解析BootStrapModel(JSON对象类型),但实际拿到的字符串可能被额外转义(比如外层带引号、内部引号转义),导致解析器误以为要解析的是String类型,而非对象,因此抛出"Expected beginning of the string, but got {"的错误。

最优解决方案:让Retrofit自动解析JSON

不要手动获取String再转换,直接通过Retrofit集成Kotlin Serialization转换器,自动完成解析:

  1. 添加依赖(确保版本匹配你的Retrofit和Kotlin Serialization版本)
implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:1.0.0"
  1. 修改Retrofit接口方法,直接返回目标数据类
@GET("bootstrap-static")
suspend fun getBootstrap(): BootStrapModel
  1. 创建Retrofit实例时配置Kotlin Serialization转换器
val retrofit = Retrofit.Builder()
    .baseUrl("https://fantasy.premierleague.com/api/")
    .addConverterFactory(Json { ignoreUnknownKeys = true }.asConverterFactory("application/json".toMediaType()))
    .build()
  1. 调用接口方法即可直接拿到解析好的BootStrapModel对象,无需手动转换。

临时修复(不推荐)

如果一定要手动处理String,先检查并清理字符串格式:

fun convert(string: String): BootStrapModel{
    // 移除外层引号并还原内部转义的引号
    val cleanedJson = string.removeSurrounding("\"").replace("\\\"", "\"")
    return Json{ignoreUnknownKeys = true}.decodeFromString(cleanedJson)
}

额外检查事项

  • 确保所有嵌套数据类(Events、GameSettings、Phases等)都添加了@Serializable注解
  • 确认所有@SerialName注解的字段名与接口返回JSON的键完全匹配

内容的提问来源于stack exchange,提问作者lvm12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 04:32:49