Say you have JSON with a field that contains a `Li...
# serialization
j
Say you have JSON with a field that contains a
List<Any?>
. In practice, the
Any?
can be (a)
null
, (b) a
String
, (c) an
Int
, or (d) another `List<Any?>. What's the best practice for deserializing this with
kotlinx.serialization
? Currently, I'm doing
@ContextualSerialization
like this:
Copy code
@Serializable
data class Items(
    val id: Int,
    val values: List<@ContextualSerialization Any?> = emptyList()
)
This seems like the right direction, except I'm not sure how to get from this to an array of usable types (e.g. String, Int, List<Any>)?
d
Copy code
@Serializable
data class Items(
    val id: Int,
    val values: JsonArray
)
?
j
@Dominaezzz That works, but from there, how do I deserialize the different types of values that appear in that
values
array into their actual types (when it could be a string, int, or list)?
this is sort of what i want to do
Copy code
@Serializable
data class Items(
    val id: Int,
    @Polymorphic val values: Value? = null
) {
    sealed class Value {
        @Serializable
        data class Array(val index: Int, val string: String? = null)

        @Serializable
        data class String(val text: String? = null)

        @Serializable
        data class Int(val index: Int? = null)
    }
}
d
Was about to suggest that.
I think that's the way to go.
j
i'll try that
i think i tried it earlier and it didn't quite work
because how do i get from the raw array case to the Array type (which just pulls the values out of the array)
d
With a custom serializer, just cast the
Decoder
to a
JsonInput
and call
decodeJson()
, then you can inspect the small part of the json tree.
@Polymorphic
wont help here.
j
what about @ContextualSerialization
part of the problem is that the field is nullable
d
You don't need it.
j
and the values in the array case are also nullable
d
Just specify the serializer statically.
j
hmm