0

I have a payload which look like this :

{
    "data": {
        "12345": {
            "is_indexable": true,
            "description": "Lorem description",
            "items": {
                "id": 2644,
                "name": "Naming here"
            }
        },
        "678910": {
            "is_indexable": false,
            "description": "Lorem description 2",
            "items": {
                "id": 29844,
                "name": "Naming here again"
            }
        }
    }
}

I wanted to generate a specific data class for that payload using tools like https://transform.tools/json-to-kotlin but it's impossible since the array inside the "data" object is an ID (so a dynamic data)

data class Root(
    val data_field: Data
)

data class Data(
    val payload: List<Payload>, // Something to represent the dynamic ids
)

data class Payload(
    val isIndexable: Boolean,
    val description: String,
    val items: Items
)

data class Items(
    val id: Long,
    val name: String
)

I don't know if I'm clear, did you have an idea to make this in a clean way ?

Thank you all !

2 Answers2

0

You need to array of map to achieve this. You are building map in map right now. It should be like following if you need array;

{
    "data": [
        { id: "12345", 
            "is_indexable": true,
            "description": "Lorem description",
            "items": {
                "id": 2644,
                "name": "Naming here"
            }
        },
        {"id" : "678910"
            "is_indexable": false,
            "description": "Lorem description 2",
            "items": {
                "id": 29844,
                "name": "Naming here again"
            }
        }
    ]
}
Muhtar
  • 1,506
  • 1
  • 8
  • 33
0

There is an amazing plugin add to the android studio where it converts this payload to suitable classes for example, the JSON has one object and inside the object, there are a lot of objects and array this tool will determine all this as classes

you can load it from this link:

https://plugins.jetbrains.com/plugin/9960-json-to-kotlin-class-jsontokotlinclass From this link, you can also know how you can use this tool

go to android studio and from file->setting->plugin->Install Plugin from disk

enter image description here

and convert it by easy and without problems

good luck

Amnah
  • 27
  • 3
  • Yes, I use this one personally https://transform.tools/json-to-kotlin but the problem is that it didn't understand that the array key 12345 is a dynamic one, so it create a Data class like this : data class N12345( val isIndexable: Boolean, val description: String, val items: Items ) Which is invalid for my case :/ – Alex Lombry Jun 27 '21 at 19:40
  • Look at this question which I think will solve your problem https://stackoverflow.com/questions/37801197/using-json-object-name-if-object-name-is-a-number – Amnah Jun 28 '21 at 16:43