指定为非null的参数为null异常,在web api上使用gson返回null

问题描述 投票:0回答:2

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

当Web api返回null时

{“events”: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>)

Match.class

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

)

android api android-studio kotlin gson
2个回答
1
投票

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

val event: Event?

0
投票

您可以使用nullable中的?制作特定对象kotlin

data class Article(
     val title: String, 
     val body: String, 
     val events: Events? = null, //Make it nullable
     val payWall: Boolean = false, 
     val titleImage: String? = null
)
© www.soinside.com 2019 - 2024. All rights reserved.