简体   繁体   中英

How can I define dynamic data class? (Android - Retrofit2)

I am developing an Android App via Kotlin. The app uses Retrofit2 for HTTP requests. I used Retrofit2 over and over but I don't know how to solve this scenario.

I want to use an API which needs a query like query1, query2 etc. (Close to 100 values available)

For Example:

When I send a request via "query1" the response object has coordinates: List<List<List<Double>>>
When I send a request via "query2" the response object has coordinates: List<List<Double>>
When I send a request via "query3" the response object has coordinates: List<List<List<List<Double>>>>
When I send a request via "query4" the response object has coordinates: List<List<Double>>

I don't know how API returns the inner list count. By the way there is just one coordinates in the object.

The response object in JSON format

[
    {
        "key-1": "value-1",
        "key-2": "value-2",
        "key-3": "value-3",
        "key-4": {
            "inner-key": [
                [
                    [
                        1.0,
                        1.0
                    ],
                    [
                        1.0,
                        1.0
                    ]
                ]
            ]
        }
    },
    {
        "key-1": "value-1",
        "key-2": "value-2",
        "key-3": "value-3",
        "key-4": {
            "inner-key": [
                [
                    [
                        [
                            1.0,
                            1.0
                        ],
                        [
                            1.0,
                            1.0
                        ]
                    ],
                    [
                        [
                            1.0,
                            1.0
                        ],
                        [
                            1.0,
                            1.0
                        ]
                    ]
                ]
            ]
        }
    }
]

Here is my data classes. But I don't know how can I define the "key4" object.

data class Response(
    val key1: String? = null,
    val key2: String? = null,
    val key3: String? = null,
    val key4: key4? = null,
)
data class key4(
    //How should I define the "inner-key" object
)

Any suggestions would be helpful.

Solution:

I tried a few way for solution. I didn't know it's perfect solution but there is my solution :

There is my data class which name is key4 on my question.

data class key4(
    val inner-key: List<Any>? = null
)

Also I cast inner-key like:

val temp = response?.key4?.inner-key as List<List<Double>>?

or

val temp = response?.key4?.inner-key as List<List<List<Double>>>?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM