如何编写一个 kotlin 数据 class 来匹配 json?
How to write a kotlin data class to match json?
我正在使用 Retrofit 调用 API 并使用 converter-gson 将响应 json 转换为 kotlin
这是回应
{
"id": "1",
"rank": "1",
"name": "Challenge",
"status": "E",
"createDate": "2018-09-17 15:01:28",
"lastModDate": "2018-09-17 15:06:32",
"category": "DINING",
"photo": {
"path": "http://example.com/xxx.jpg",
"size": [
400,
267
]
}
}
这是数据 class。
data class ServiceList (val id:Int,
val rank:Int,
val name:String,
val status:String,
val lastModDate:String,
val category:String,
???????)
如何完成这个class?
您可以声明另一个 data class
来描述 photo
属性,如下所示:
data class ServiceList(val id: Int,
val rank: Int,
val name: String,
val status: String,
val lastModDate: String,
val category: String,
val photo: Photo) {
data class Photo(val size: List<Int>, val path: String)
}
如果Photo
也被用在其他环境中,你可以把它拉出来成为顶层class:
data class ServiceList (val id: Int,
val rank: Int,
val name: String,
val status: String,
val lastModDate: String,
val category: String,
val photo: ServiceListPhoto)
data class ServiceListPhoto(val size: List<Int>, val path: String)
我正在使用 Retrofit 调用 API 并使用 converter-gson 将响应 json 转换为 kotlin
这是回应
{
"id": "1",
"rank": "1",
"name": "Challenge",
"status": "E",
"createDate": "2018-09-17 15:01:28",
"lastModDate": "2018-09-17 15:06:32",
"category": "DINING",
"photo": {
"path": "http://example.com/xxx.jpg",
"size": [
400,
267
]
}
}
这是数据 class。
data class ServiceList (val id:Int,
val rank:Int,
val name:String,
val status:String,
val lastModDate:String,
val category:String,
???????)
如何完成这个class?
您可以声明另一个 data class
来描述 photo
属性,如下所示:
data class ServiceList(val id: Int,
val rank: Int,
val name: String,
val status: String,
val lastModDate: String,
val category: String,
val photo: Photo) {
data class Photo(val size: List<Int>, val path: String)
}
如果Photo
也被用在其他环境中,你可以把它拉出来成为顶层class:
data class ServiceList (val id: Int,
val rank: Int,
val name: String,
val status: String,
val lastModDate: String,
val category: String,
val photo: ServiceListPhoto)
data class ServiceListPhoto(val size: List<Int>, val path: String)