Android 检索JSON中的特定字段

Android 检索JSON中的特定字段,android,kotlin,gson,retrofit,Android,Kotlin,Gson,Retrofit,我有一个数据类,它表示我从API接收的对象: 数据类MyObject( @SerializedName(“id”)变量id:Int, @SerializedName(“status.description”)变量状态:字符串 ) 这就是我的JSON的样子: { "id": 1, "status": { "description": "OK" } } 我使用Gsonadapter通过改装获取这些数据,但我的status属性始终为null。即使我使用Mos

我有一个数据类,它表示我从API接收的对象:

数据类MyObject(
@SerializedName(“id”)变量id:Int,
@SerializedName(“status.description”)变量状态:字符串
)
这就是我的JSON的样子:

{
    "id": 1,
    "status": {
        "description": "OK"
    }
}
我使用
Gson
adapter通过改装获取这些数据,但我的status属性始终为null。即使我使用
Moshi
它仍然是null

如何从JSON中获取此属性,而不必创建一个只有一个名为description的唯一属性的类
Status

data class MyObject(
    @SerializedName("id") var id: Int,
    @SerializedName("status") var status: Status
)

data class Status(
    @SerializedName("description") var description: String,
)
如果您不想使用上述方法:

您可以使用
val
使这些字段成为最终字段。还有一个技巧需要记住,如果您使用final字段,kotlin可以为您制作smartcast

例如:

data class Status(
    val description: String?
)

val status: Status = Status("success")
if ( status.description != null){
  // status.description will be smartcasted to String, not String?
}

有一个很酷的json处理库,教程:除了这个正确答案之外,如果字段与json字段具有相同的名称,则可以省略使用@SerializedName注释
data class Status(
    val description: String?
)

val status: Status = Status("success")
if ( status.description != null){
  // status.description will be smartcasted to String, not String?
}