Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 775
Robertas Setkus Avatar asked Apr 23 '26 06:04

Robertas Setkus


1 Answers

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)
like image 143
Dominik Avatar answered Apr 24 '26 23:04

Dominik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!