Generate Data class on dynamic value inside a JSON payload

1k Views Asked by At

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

There are 2 best solutions below

1
Muhtar On

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"
            }
        }
    ]
}
2
Amnah On

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