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

调用MangaUpdates API时Gson类型转换异常排查求助

解决MangaUpdates API Gson解析NumberFormatException问题

问题核心

Gson解析API响应时,$.series_id字段实际返回的68203991471超出了Java/Kotlin的Int类型范围(Int最大值为2147483647),但你的WebtoonJson数据类中该字段定义为Int类型,直接导致类型转换失败。

解决方案

1. 修正数据类字段类型(核心解决步骤)

直接把WebtoonJson里的series_id字段类型从Int改成Long:

data class WebtoonJson(
    val series_id: Long, // 替换原有的Int类型
    // 其他字段保持不变...
)

68203991471完全在Long的取值范围内(Long最大值为9223372036854775807),这一步就能直接解决解析异常。

2. 路径参数的可选调整

虽然API会自动将ID编码为base36,若你需要手动传递base36格式的ID,可修改接口参数类型为String:

interface ApiService {
    @GET("v1/series/{id}")
    suspend fun getWebtoonApi(@Path("id") id: String = "vbyw8mn"): Response<WebtoonJson>
}

注意:这一步不是解决当前解析异常的关键,仅针对参数传递方式的调整。

3. 自定义Gson适配器(特殊场景备用)

如果无法修改数据类字段类型,可自定义适配器强制将超大整数转为Long:

class LongTypeAdapter : TypeAdapter<Long>() {
    override fun write(out: JsonWriter, value: Long?) {
        out.value(value)
    }

    override fun read(`in`: JsonReader): Long {
        return try {
            `in`.nextLong()
        } catch (e: NumberFormatException) {
            `in`.nextString().toLong()
        }
    }
}

然后在构建Retrofit时注册该适配器:

val gson = GsonBuilder()
    .registerTypeAdapter(Long::class.java, LongTypeAdapter())
    .create()

private val retrofit = Retrofit.Builder()
    .baseUrl("https://api.mangaupdates.com/")
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build()

验证步骤

  1. 修改数据类字段类型后重新编译运行
  2. 调用API检查是否仍抛出NumberFormatException
  3. 确认响应数据中的series_id已被正确解析为Long类型

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:52:47