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

时间:2018-09-11 08:59:26

标签: android api android-studio kotlin gson

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

当Web api返回null

  

{“事件”: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

2 个答案:

答案 0 :(得分:1)

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

ActiveSheet.Cells(ActiveWindow.ScrollRow, 6).Show 'Scroll to the 6th column, Column F

答案 1 :(得分: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
)