首页 > 解决方案 > java.lang.IllegalArgumentException: 将 JSON 解析为 kotlin 数据类时指定为非 null 的参数为 null

问题描述

在 kotlin 成为 android 的第一语言之后,我就全身心投入到了它。随着这些天的一点点进步,我一直在将我现有的知识迁移到 kotlin。最近,我正在学习如何在一个虚拟项目中使用 GSON、Retrofit 和 kotlin。

CurrentWeather是在视图中显示数据的模型

data class CurrentWeather(
    val latitude: Double,
    val longitude: Double,
    val placeName: String,
    val temperature: Float,
    val maxTemperature: Float,
    val minTemperature: Float,
    val windSpeed: Float,
    val windDirection: Float,
    val weatherType: String,
    val weatherDescription: String,
    val icon: String,
    val timestamp: Instant)

classCurrent负责将 JSON 解析为 POJO 类,就像我过去所做的那样,但今天使用 kotlin 看起来有点不同

data class Current(@SerializedName("coord") val location: Location,
          @SerializedName("weather") val weather: List<Weather>,
          @SerializedName("main") val temperatureAndPressure: TemperatureAndPressure,
          @SerializedName("wind") val wind: Wind,
          @SerializedName("dt") val timeStamp: Long,
          @SerializedName("name") val placeName: String) {

val time: Instant by fastLazy { Instant.ofEpochSecond(timeStamp) }


val currentWeather = CurrentWeather(location.latitude,
        location.longitude,
        placeName,
        temperatureAndPressure.temperature,
        temperatureAndPressure.maxTemperature,
        temperatureAndPressure.minTemperature,
        wind.windSpeed ?: 0f,
        wind.windAngle ?: 0f,
        weather[0].main,
        weather[0].description,
        weather[0].icon,
        time)
 }

即使我从改造中获得了成功的响应(我已经检查了成员变量;例如位置:位置,天气:列表,温度和压力:温度和压力等。但是,我收到了这个错误。

2018-11-12 21:04:07.455 9948-9948/bus.green.fivedayweather E/AndroidRuntime:致命异常:主进程:bus.green.fivedayweather,PID:9948 java.lang.IllegalArgumentException:参数指定为非空为空:方法 kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull,参数 p1 在 bus.green.fivedayweather.ui.CurrentWeatherFragment$retrieveForecast$1.invoke(Unknown Source:6) at bus.green.fivedayweather.ui.CurrentWeatherFragment$retrieveForecast$1 .invoke(CurrentWeatherFragment.kt:20) at bus.green.fivedayweather.net.OpenWeatherMapProvider$RetrofitCallbackWrapper.onResponse(OpenWeatherMapProvider.kt:62)

我在解析时做错了吗?

标签: androidjsonkotlingson

解决方案


这是你的问题Parameter specified as non-null is null。您所有的数据类都用non-null parameter constructor. 但是,在解析 JSON 过程中,有一个空参数 --> 导致崩溃。要解决此问题,您应该将构造函数参数声明为可为空,如下所示:

data class Current(@SerializedName("coord") val location: Location?,
      @SerializedName("weather") val weather: List<Weather>?,
      @SerializedName("main") val temperatureAndPressure: TemperatureAndPressure?,
      @SerializedName("wind") val wind: Wind?,
      @SerializedName("dt") val timeStamp: Long?,
      @SerializedName("name") val placeName: String?) {
// your CurrentWeather class should be the same. 
// Of course, if you are sure with non-null parameters, you should make them non-null.

推荐阅读