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
相关产品推荐
相关产品推荐

