https://kotlinlang.org logo
#android
Title
# android
t

Tony

04/15/2020, 3:22 PM
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?
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
List<String>
since that sounds like what it should be. https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/custom_serializers.md
t

Tony

04/15/2020, 5:24 PM
How do I check if the decoder/encoder is a specific type? or will it map automatically?
c

Cody Engel

04/15/2020, 5:29 PM
I'm not positive, I'd check the functions offered by decoder/encoder. It looks like they have
decodeString()
so if there is a
decodeList
and both of them throw an exception, worst case is you can check for those exceptions as a crude if/else
Serialization is still fairly new though so always a chance you'll run into something that isn't full there yet