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

Gson泛型JSON解析失败求解决方案或替代库推荐

解决Gson泛型JSON解析问题&替代库推荐

这问题我之前踩过一模一样的坑!核心原因是Java/Kotlin的类型擦除机制——当你在泛型方法或类里直接用object : TypeToken<T>() {}.type时,运行时JVM会把泛型参数T擦除成Object,Gson根本拿不到你实际要解析的UserInfo类型,自然解析失败。下面给你两种解决思路:

一、修复Gson的泛型解析问题

1. 用Kotlin的inline reified函数(最推荐)

Kotlin的reified关键字能保留泛型的实际类型信息,配合inline函数就能让Gson正确识别目标类型。写个扩展函数就行:

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

inline fun <reified T> Gson.fromJsonGeneric(json: String): T? {
    return this.fromJson(json, object : TypeToken<T>() {}.type)
}

调用的时候直接指定泛型类型,不管是单个对象还是列表都能搞定:

// 解析单个UserInfo
val userInfo = gson?.fromJsonGeneric<UserInfo>(khttpResponse.jsonObject.toString())

// 解析UserInfo列表(如果需要的话)
val userList = gson?.fromJsonGeneric<List<UserInfo>>(khttpResponse.jsonObject.toString())

2. 提前传入TypeToken

如果你的泛型逻辑是在类里实现的,没法用reified,可以在创建类实例时手动传入TypeToken,把具体类型信息带进去:

class GenericClient<T>(private val typeToken: TypeToken<T>) {
    private val gson = Gson()

    fun parseJson(json: String): T? {
        return gson.fromJson(json, typeToken.type)
    }
}

// 使用示例
val userClient = GenericClient(object : TypeToken<UserInfo>() {})
val userInfo = userClient.parseJson(khttpResponse.jsonObject.toString())

二、推荐更适合Kotlin的JSON解析库

如果觉得Gson的泛型处理太麻烦,试试下面这两个对Kotlin更友好的库:

1. Moshi

Square出品的库,天生支持Kotlin的data class,泛型处理更简洁,还能避免很多Gson的坑。
写解析代码示例:

import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory

val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory()) // 必须添加这个支持Kotlin
    .build()

// 解析单个UserInfo
val userAdapter = moshi.adapter<UserInfo>()
val userInfo = userAdapter.fromJson(khttpResponse.jsonObject.toString())

// 解析列表的话,用Types生成参数化类型
import com.squareup.moshi.Types
val listType = Types.newParameterizedType(List::class.java, UserInfo::class.java)
val listAdapter = moshi.adapter<List<UserInfo>>(listType)
val userList = listAdapter.fromJson(khttpResponse.jsonObject.toString())

同样也可以写inline reified扩展函数简化调用。

2. Jackson

老牌JSON库,添加Kotlin模块后对Kotlin的支持也很完善:

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule

val objectMapper = ObjectMapper().registerKotlinModule()

// 解析单个UserInfo
val userInfo = objectMapper.readValue<UserInfo>(khttpResponse.jsonObject.toString())

// 解析列表
val userList = objectMapper.readValue<List<UserInfo>>(khttpResponse.jsonObject.toString())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:25:50