Search code examples
jsonkotlinserializationdeserializationkotlin-multiplatform

Kotlin Serialization - Decoding JSON Array from string


Trying to deserialize cached json string to data object and getting exception: kotlinx.serialization.json.internal.JsonDecodingException: Expected class kotlinx.serialization.json.JsonObject (Kotlin reflection is not available) as the serialized body of kotlinx.serialization.Polymorphic<List>, but had class kotlinx.serialization.json.JsonArray (Kotlin reflection is not available)

Code used to deserialize

internal inline fun <reified R : Any> String.convertToDataClass() =
    Json {
        ignoreUnknownKeys = true
    }.decodeFromString(R::class.serializer(), this)

Code example:

val jsonString  ="""
[{"name1":"value1"}, {"name2":"value2"}]
"""
val dataObject = jsonString.convertToDataClass<List<SomeObject>>()

When going through Ktor pipeline everything works fine but it is breaking on attempt to deserialize the same response body cached as string.

I am aware of that R::class.serializer() is marked as for internal usage but this is the only way known to me how to deserialize generics from string content.


Solution

  • There is a fitting extension function available at kotlinx.serialization.decodeFromString that takes one generic parameter, so you could pass R as generic to that extension.

    Check https://github.com/Kotlin/kotlinx.serialization#introduction-and-references. The sample is val obj = Json.decodeFromString<Project>(string), which will fit your needs doing something like this

    import kotlinx.serialization.decodeFromString
    import kotlinx.serialization.json.Json    
    
    internal inline fun <reified R : Any> String.convertToDataClass() =
        Json {
            ignoreUnknownKeys = true
        }.decodeFromString<R>(this)