Kotlinx.serialization: Custom serializer to keep nested object as plain JSON format

Created on 25 Jan 2019  路  2Comments  路  Source: Kotlin/kotlinx.serialization

Hi,

Is there a way to create a custom serializer that would keep a nested object as plain JSON format ?

For instance, I've got the following JSON data:

{
    "id": "v1",
    "index": {
        "data": "value"
    }
}

And the following data class and custom serializer:

@Serializable
data class MyData {

    var id: String = "" // expecting "v1"

    @Serializable(with = IndexSerializer::class)
    var index: String = "" // expecting "{ "data": "value" }"
}

object IndexSerializer : KSerializer<String> {

    override val descriptor: SerialDescriptor
        get() = StringDescriptor.withName("index")

    override fun serialize(output: Encoder, obj: String) {
        // Does nothing for now
    }

    override fun deserialize(input: Decoder): String {
        return "" // Not sure how to retrieve plain JSON
    }
}

But I get the following error:

kotlinx.serialization.json.JsonParsingException: Invalid JSON at 24: Expected string or non-null literal

Any idea on how to avoid this error and retrieve nested JSON ?
Thanks

json question

Most helpful comment

You can cast input in IndexSerializer to JsonInput and then use .decodeJson to obtain JsonElement. Its .toString() can give you what you want.

All 2 comments

You can cast input in IndexSerializer to JsonInput and then use .decodeJson to obtain JsonElement. Its .toString() can give you what you want.

Works great, thanks!

Was this page helpful?
0 / 5 - 0 ratings