'How to handle two data type in the same API android
I have an API response. When data is purchased it gives as a JSONObject else a null string.
How do I process both the data types. If I try to specify Any as the data type is model class, I am not able to retrieve the data in the JSONObject.
Solution 1:[1]
If it's just a null, you can simply check if the key exists before calling getString:
private fun JSONObject.getStringOrNull(key: String): String? {
return when {
this.has(key) -> try { getString(key) } catch (e: Exception) { null }
else -> null
}
}
@Test
fun runTest() {
val json = """
{ "name":"Bob Ross", "email":null }
""".trimIndent()
val obj = JSONObject(json)
val name = obj.getStringOrNull("name")
val email = obj.getStringOrNull("email")
println(name)
println(email)
}
Solution 2:[2]
You can use JsonElement to store the data in the model class.Since primitive data types also extend JsonElement
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris |
| Solution 2 | Nikitha |
