Suppose I have a JSON string like this: `[36, {"co...
# serialization
u
Suppose I have a JSON string like this:
[36, {"color": "orange", "sizes": [23, 42, 7]}]
(so a mixed JSON array) where the first entry of the array is always an
Int
that represents a type of message and the second is an arbitrary map payload. I, as a library, need to parse the type field to do some things, but I don't care about the payload and would like to deserialize into a type that is provided by my users. E.g.
fun <UserType> parseMessage(json: String): UserType
Can this be done via kotlinx serialization?
Of course I can just use
JsonElement
everywhere, but that would be cumbersome for my clients to use, because then they would have to map the elements to domain classes themselves.
I could also deserialize into
JsonElement
, extract the elements that are relevant to my library, serialize the payload again and then deserialize it with a user-provided serializer. But that seems really inefficient.
I'm wondering if it's at all possible to customize the deserialization in a way that combines the best of both worlds.