Hello, I have a question about data classes and types. I have an API where it returns a field called text. Text can either have the type of String or type List<Object>. How would I handle creating a data class for this?
c
Cody Engel
04/15/2020, 3:27 PM
Are you consuming the API or producing the API?
Cody Engel
04/15/2020, 3:28 PM
Whoops, scratch that, just saw this in #android so probably consuming it...
What JSON library are you using?
t
Tony
04/15/2020, 3:32 PM
Kotlinx Serialization
c
Cody Engel
04/15/2020, 5:22 PM
Gotcha, @Tony have you tried setting
text
to
Any
? It's not a great solution, but could be the quickest/easiest.
The next option would be looking at custom serializers (linked in this message). The way I'd look to build it out is you'd have a sealed class with data classes inside of it, something like this:
Copy code
sealed class ApiResponse<T> {
abstract text: T
data class AsString<String>(override text: String): ApiResponse()
data class AsList<List<Any>>(override text: List<Any>>): ApiResponse()
}
The above example was just typed in Slack so probably not perfect but that's the general idea. Then your customer serializer would handle the different scenarios. If you have control over the API then I'd recommend asking the engineers to update it to just return a