如何使用kotlinx.serialization解码泛型列表?解码报错求助
解决Kotlin序列化JSON解码异常问题
问题场景
给定如下JSON数据:
{"code":200,"msg":"111",data:[{"name":"va","list":[{"code":"11"}]},{"name":"va","list":[{"code":"11"}]}]}
对应的Kotlin序列化类定义:
@Serializable class ServerResponse<T> { @SerialName(value = "code") var code = 0 @SerialName(value = "msg") var msg: String? = null @SerialName(value = "data") var data: T? = null private set } @Serializable data class PluginInfo( @SerialName(value = "name") val name: String, @SerialName(value = "list") val list: MutableList<PluginConfig> ) @Serializable data class PluginConfig( @SerialName(value = "code") val code: String )
执行解码代码时抛出异常:
val response = json.decodeFromString<ServerResponse<MutableList<PluginInfo>>>(pluginInfoJson)
异常信息:
kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 271: Expected quotation mark '"', but had '1' instead at path: $.data[0].
问题原因
- JSON格式不合法:标准JSON要求所有键必须用双引号包裹,原始JSON中的
data键未加双引号,属于非标准格式,导致解析器无法正确识别键值结构。 - 默认解析器严格遵循JSON规范,对非标准格式直接抛出解码异常。
解决方案
方案1:修正JSON为标准格式(推荐)
将未加引号的data键改为"data",修正后的JSON如下:
{"code":200,"msg":"111","data":[{"name":"va","list":[{"code":"11"}]},{"name":"va","list":[{"code":"11"}]}]}
修正后使用原解码代码即可正常解析。
方案2:配置宽松解析(无法修改原始JSON时使用)
如果无法修改原始JSON,可以配置Json实例允许解析非标准格式:
val json = Json { isLenient = true // 允许无引号的键、尾随逗号等非标准格式 ignoreUnknownKeys = true // 忽略未知字段,增强容错性 }
使用这个配置的json实例执行解码操作,即可兼容非标准JSON。
内容的提问来源于stack exchange,提问作者Gary
相关产品推荐
相关产品推荐

