Search code examples
kotlinjson-deserializationkotlinx.serialization

What should be the Kotlin class to represent a json with array of classes


Given the following JSON:

{
"from": 1,
"to": 3,
"results": [
    {
        "item": {
            "status": "SUCCESS",
            "statusMessage": "",
            "requestId": "1"
        }
    },
    {
        "item": {
            "status": "SUCCESS",
            "statusMessage": "",
            "requestId": "2"
        }
    },
    {
        "item": {
            "status": "SUCCESS",
            "statusMessage": "",
            "requestId": "3"
        }
    },
    {
        "item": {
            "status": "SUCCESS",
            "statusMessage": "",
            "requestId": "4"
        }
    }
]}

What should be the correct Kotlin classes to define in order to de-serialize using kotlinx.serialization.json.Json?

I have tried:

data class Response (
  val from: Long,
  val to: Long,
  val results: List<Result>
)

data class Result (
  val item: List<Item>
)

data class Item (
  val status: String,
  val statusMessage: String,
  val requestID: String
)

My attempt does not describe the list of items correctly. What am I doing wrong?


Solution

  • Each of your Results have exactly one Item with the key "item", so it should be:

    data class Result (
      val item: Item
    )