Kotlin调用OpenWeatherMap API时如何解析响应体获取对应字段值
Kotlin 读取OpenWeatherMap接口JSON字段的正确方式
你写的链式调用无法生效,是因为JSONObject.get()方法默认返回Any类型,Kotlin不会自动识别它是数组还是对象,需要手动做类型转换后才能继续访问内部字段。
OpenWeatherMap返回的结构中,weather字段是JSON数组,数组第一个元素才是包含description的JSON对象,正确的写法如下:
override fun onResponse(call: Call, response: Response) { // 先判空,避免响应体为空崩溃 val bodyStr = response.body?.string() ?: return val body = JSONObject(bodyStr) // 先获取weather数组,再取第一个元素转为JSONObject,最后取description字段 val weatherArray = body.getJSONArray("weather") val weatherItem = weatherArray.getJSONObject(0) val description = weatherItem.getString("description") findViewById<TextView>(R.id.weatherDescription).text = description }
优化建议
- 可以用
optXXX系列方法替代getXXX方法,字段不存在时会返回null而非抛出异常,容错性更高:val description = body.optJSONArray("weather") ?.optJSONObject(0) ?.optString("description") ?: "暂无天气描述" - 如果需要解析的字段较多,更推荐使用Gson、Moshi等JSON序列化库,提前定义对应结构的Kotlin数据类,直接将JSON字符串转为实体对象,无需手动逐个读取字段,示例如下:
// 定义数据类 data class WeatherResponse(val weather: List<WeatherItem>) data class WeatherItem(val description: String) // 解析时直接转换 val weatherResponse = Gson().fromJson(bodyStr, WeatherResponse::class.java) val description = weatherResponse.weather.firstOrNull()?.description ?: "暂无天气描述"
内容的提问来源于stack exchange,提问作者philale
相关产品推荐
相关产品推荐

