Home > Net >  How to parse json array which contains multiple data types?
How to parse json array which contains multiple data types?

Time:03-17

I am getting two types of data in json array from API Response: String and json object

 JSON::
{
"elements": [
    "task.",
    "weeks.",
    {
        "image_url": "https://www.graph-2x.jpg"
    }
]
}

data class::
  @SerializedName("elements" ) var bodyElements : ArrayList<String> = arrayListOf()

It throws error as I have mentioned data type is String. Can any one please suggest that how can I parse the multiple type json array in Kotlin? Thanks in advance.

CodePudding user response:

For this specific JSON format you can use the following:

Use Any as data type:

data class ElementsResponse(@SerializedName("elements") val elements: ArrayList<Any>)

And to consume the response, check if Any is String or LinkedTreeMap

when(element) {
    is String -> {
        // task. or weeks.
        println("string: $element")
    }
    is LinkedTreeMap<*, *> -> {
        // key: image_url / value: https://www.graph-2x.jpg
        println("image_url: ${element["image_url"]}")
    }
}
  • Related