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

Kotlin如何从JSON数组内嵌的JSON对象中提取单个value字段值

Kotlin JSON字段取值问题修复方案

核心问题

代码报错的根本原因是字段类型不匹配:JSON结构中forecastMaxtemp下的value是数值类型(无引号包裹的31),调用getString()方法取字符串类型值会触发类型不匹配异常。

修复代码

直接将最后取值方法替换为数值类型的取值方法,再转字符串赋值给TextView即可:

Response.Listener { response ->
    temp.text = response.getJSONArray("weatherForecast")
        .getJSONObject(0)
        .getJSONObject("forecastMaxtemp")
        .getInt("value")
        .toString()
},

稳定性优化建议

如果要避免JSON结构变动、字段缺失导致的崩溃,推荐用opt系列方法替代get系列方法,搭配异常捕获处理边界场景:

Response.Listener { response ->
    val tempValue = runCatching {
        response.optJSONArray("weatherForecast")
            ?.optJSONObject(0)
            ?.optJSONObject("forecastMaxtemp")
            ?.optInt("value")
            ?.toString() ?: "暂无温度数据"
    }.getOrDefault("暂无温度数据")
    temp.text = tempValue
},

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 01:06:03