如何防止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
)
MatchResponse类的事件变量是否可以为空?就像是:
val event: Event?
您可以使用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
)