【发布时间】:2020-05-31 05:50:41
【问题描述】:
我的 api 响应有如下数据类
data class ApiResponse(
@SerializedName("ErrorCode") @Expose
var errorCode: Int = 0,
@SerializedName("Message")
@Expose
var message: String? = null,
@SerializedName("Token")
@Expose
var token: String? = null,
@SerializedName("UserId")
@Expose
var userId: String? = null,
@SerializedName("DOB")
@Expose
var birthdate: String? = null,
@SerializedName("Mobile")
@Expose
var mobile: String? = null,
@SerializedName("Data")
@Expose
var dataList: MutableList<Data?>? = null
)
我的 api 调用
val request = ApiServiceBuilder.buildService(NetworkCall::class.java)
request.login(apiPost = ApiPost("long","hello")).enqueue(object :Callback<ApiResponse>{
override fun onResponse(call: Call<ApiResponse>, response: Response<ApiResponse>) {
Log.e("resopne",response.body().userId)
}
override fun onFailure(call: Call<ApiResponse>, t: Throwable) {
t.printStackTrace()
Log.e("resopne","error")
}
})
在尝试获取 userId 时,我得到了
在可空对象上只允许安全或非空断言调用
【问题讨论】:
-
您的数据类变量
var userId: String? = null可以为空。不能直接拨打response.body().userId,加!!到最后response.body().userId!!但如果 userId 值为 null,这将导致 nullPointerException。更多详情请参考kotlinlang.org/docs/reference/null-safety.html。
标签: android kotlin data-class