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.
Ras generic parameter fordecodeFromString?Ras a parameter if you're usingJsonclass functiondecodeFromString. However, your question has led to me to find thatStringFormathas extension function with same name but different definition, where you can passRas a parameter. Switching to it, solved the error.Json.decodeFromString<R>(this)?fun <T> decodeFromString(deserializer: DeserializationStrategy<T>, string: String): Tval obj = Json.decodeFromString<Project>(string)so there should be a fitting overload.