Search code examples
kotlinoop

Kotlin beginner cannot get Response object shape right


I am brand new Kotlin. I am trying to recreate this response object

 Response:
 {"
     id":"abc123",
     "cat1": {
         "key1":"value1",
         "key2":"value2"
     },
     "cat2": {
         "key3":"value3"
     }
 }

but this does not appear to be possible when creating a data class

val id: String,
val category: String, Map<String, String>

This is what I have so far:

 data class ResponseObject(
     val id: String,
     val category: Map<Category, Map<String, String>>
 )

** Category is an enum class **

I get this

 {"
     id":"abc123",
     "category: {
         "cat1": {
           "key1":"value1",
           "key2":"value2"
         },
         "cat2": {
           "key3":"value3"
         }
     }

}

Any help is appreciated!


Solution

  • Maybe this:

    import com.google.gson.Gson
    
    data class ResponseObject(val id:String, val cat1:Map<String,String>, val cat2:Map<String,String>)
    
    fun main(args: Array<String>) {
        val cat1 = mapOf<String,String>(Pair("key1", "value1"), Pair("key2", "value2"))
        val cat2 = mapOf<String,String>(Pair("key3", "value3"))
        val obj = ResponseObject("abc123", cat1, cat2)
    
        val g = Gson()
        val json = g.toJson(obj)
    
        println(json)
    
    }
    

    prints:

    {"id":"abc123","cat1":{"key1":"value1","key2":"value2"},"cat2":{"key3":"value3"}}

    Which when un-minified is this:

    {
        "id":"abc123",
        "cat1":{
             "key1":"value1",
             "key2":"value2"
        },
        "cat2":{
            "key3":"value3"
        }
    }