Erez Ben Harush
Erez Ben Harush

Reputation: 867

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?

Upvotes: 1

Views: 588

Answers (3)

sir
sir

Reputation: 126

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

Upvotes: 1

Akshay Sensussoft
Akshay Sensussoft

Reputation: 51

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

Upvotes: 1

Dmitry Kaznacheev
Dmitry Kaznacheev

Reputation: 66

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

data class Result (
  val item: Item
)

Upvotes: 5

Related Questions