Search code examples
jsonkotlindata-class

How to write a kotlin data class to match json?


I am using Retrofit to call API and using converter-gson to convert response json to kotlin

This is response

{
    "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
        ]
    }
}

And this is data class.

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

How to complete this class?


Solution

  • You can declare another data class to describe the photo property like so:

    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)
    }
    

    If the Photo is to be used in other contexts as well you can pull it out to be a top level 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)