0

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?

Erez Ben Harush
  • 833
  • 9
  • 26

3 Answers3

5

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

data class Result (
  val item: Item
)
1

You can write a class like below.

data class Temp(
    val from: Int, // 1
    val results: List<Result>,
    val to: Int // 3
) {
    data class Result(
        val item: Item
    ) {
        data class Item(
            val requestId: String, // 1
            val status: String, // SUCCESS
            val statusMessage: String
        )
    }
}
1

Everything is fine except the Result class. In JSON, arrays are kept between square brackets, like this: [a, b, c]. Notice that you have no square brackets in the Result.

Nevertheless, don't spend too much time with these kinds of problems. Use JSON to POJO converters instead.

https://json2csharp.com/json-to-pojo

Also, this StackOverflow link might be useful:

Create POJO Class for Kotlin

sir
  • 116
  • 4