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

Kotlin中Moshi解析OpenWeatherMap数据值错误/字段为空问题

问题解决:Moshi解析OpenWeatherMap数据字段为null且温度值错误

核心问题分析

  1. 部分字段解析为null:feelsLike、tempMin、tempMax等字段在JSON中存在有效值,但解析后为null
  2. 温度值异常:解析出的temp=298.26是开尔文温度,而非请求的摄氏温度

解决方案

1. 修复字段解析为null的问题

检查Moshi依赖与配置

确保项目中正确添加了Moshi Kotlin代码生成依赖,并且配置了Kotlin适配器:

  • 在模块级build.gradle中添加代码生成依赖(根据使用的注解处理器选择kapt或KSP):

    // 如果使用kapt
    kapt "com.squareup.moshi:moshi-kotlin-codegen:1.14.0"
    // 如果使用KSP(推荐)
    ksp "com.squareup.moshi:moshi-kotlin-codegen:1.14.0"
    

    同时确保基础依赖存在:

    implementation "com.squareup.moshi:moshi:1.14.0"
    implementation "com.squareup.moshi:moshi-kotlin:1.14.0"
    
  • 创建Moshi实例时必须添加KotlinJsonAdapterFactory:

    val moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()
    

    缺少这个工厂会导致Moshi无法正确处理Kotlin数据类的注解和字段映射。

验证字段注解匹配

确认@Json(name = "...")注解的字段名与JSON中的键完全一致,你的代码中feels_like、temp_min等注解是正确的,无需修改。


2. 修复温度值异常问题

解析出的298.26是开尔文温度,说明网络请求未正确传递units=metric参数,导致API返回默认的开尔文温度。

  • 检查网络请求代码,确保请求参数中包含units=metric:
    例如使用Retrofit的接口方法:
    interface WeatherApi {
        @GET("data/2.5/forecast")
        suspend fun getForecast(
            @Query("q") city: String,
            @Query("units") units: String = "metric",
            @Query("appid") apiKey: String
        ): Response<ForecastResponse>
    }
    
    确认调用时units参数正确传递为metric。

3. 空安全优化(避免视图崩溃)

你的Main类中的字符串转换方法未做空安全处理,当字段为null时会抛出空指针异常,建议修改为:

fun getTempString(): String {
    return temp?.toString()?.substringBefore(".")?.plus("°") ?: "N/A"
}

fun getHumidityString(): String {
    return humidity?.toString()?.plus("%") ?: "N/A"
}

fun getTempMinString(): String {
    return tempMin?.toString()?.substringBefore(".")?.plus("°") ?: "N/A"
}

fun getTempMaxString(): String {
    return tempMax?.toString()?.substringBefore(".")?.plus("°") ?: "N/A"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:15:30