The following issue occurred while calling api using Retrofit on Android
Response json
[
{
"test1": 10,
"test2": 20,
"test3": 37,
"test_list": [
{
"id": 11,
"content": "AAA"
}
]
},
{
"test1": 23,
"test2": 37,
"test3": 62,
"test_list": [
{
"id": 13,
"content": "AAA"
}
]
},
[
{
"test1": 33,
"test2": 17,
"test3": 67,
"test_list": [
{
"id": 15,
"content": "BBB"
}
]
}
]
]
There's a dynamic JsonObject in the JsonArray
//dynamic
{
"test1": 23,
"test2": 37,
"test3": 62,
"test_list": [
{
"id": 13,
"content": "AAA"
}
]
}
If only this part exists, it can be solved in this way, but at the same time, there is a JsonArray, and the format of the JsonObject inside is the same as the JsonObject outside
//Impossible because of JsonArray
data class Response(
val data : List<POJO>
)
The Response json format cannot be changed If anyone knows the answer, please help. Thank you
You can use a combination of Kotlin data classes and some manual parsing. Since the structure inside the JSON array can change, you'll need to use a custom deserializer to handle the dynamic JSON objects.
First, create the data classes for your JSON structure:
Now, create a custom deserializer to handle the dynamic JSON objects within the JSON array. You can use Gson for this purpose. Add the following extension function to your code:
Now, you can use Retrofit with this custom deserializer in your API interface:
In this way, Retrofit and Gson can be used to deserialize JSON responses to dynamic JSON objects within a JSON array.