如何编写Kotlin数据类以匹配json?

时间:2018-09-21 05:47:50

标签: json kotlin data-class

我正在使用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
        ]
    }
}

这是数据类。

data class ServiceList (val id:Int,
                        val rank:Int,
                        val name:String,
                        val status:String,
                        val lastModDate:String,
                        val category:String,
                        ???????)

如何完成本课程?

1 个答案:

答案 0 :(得分:6)

您可以声明另一个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也要在其他上下文中使用,则可以将其拔出为顶级类:

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)