首页 > 解决方案 > 指定为非 null 的参数为 null 异常,在 web api 上使用 gson 返回 null

问题描述

如何防止 gson 从 web api 接收空对象

当 Web api 返回 null

{ “事件”:空 }

会变成这个例外

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter data

Gson 用法

val data = gson.fromJson(apiRepository
                .doRequest(TheSportDBApi.getLatestMatch(league)),
                MatchResponse::class.java)

我的数据类

data class MatchResponse (val events: List<Match>)

匹配类

data class Match(
    @SerializedName("idEvent")
    var eventId: String? = null,

    @SerializedName("strDate")
    var matchDate: String? = null,


    //home
    @SerializedName("strHomeTeam")
    var homeTeam: String? = null,

    @SerializedName("intHomeScore")
    var homeScore: String? = null,

    var homeBadger:String?=null,


    //away
    @SerializedName("strAwayTeam")
    var awayTeam: String? = null,

    @SerializedName("intAwayScore")
    var awayScore: String? = null,

    var awayBadge: String? = null

)

标签: androidapiandroid-studiokotlingson

解决方案


MatchResponse 类的事件变量是否可以为空?就像是:

val event: Event?

推荐阅读