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
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!
Most helpful comment
You can cast
inputinIndexSerializertoJsonInputand then use.decodeJsonto obtain JsonElement. Its.toString()can give you what you want.