Is there any way to serialize a generic/Any object...
# serialization
c
Is there any way to serialize a generic/Any object, if the actual implementation class was marked with
@Serializable
? I have a lot of classes marked with
@Serializable
, but would like to have a single function to serialize them into JSON. For instance, something like
fun Any.toJson(): String = serializer.encodeToString(this)
Here’s what I’ve tried:
Copy code
class JsonTest {

    val serializer = Json {
        serializersModule = SerializersModule {
            contextual(MyModel.serializer())
        }
    }

    // this works
    fun MyModel.toModelJson(): String = serializer.encodeToString(this)

    // this does not
    fun Any.toJson(): String = serializer.encodeToString(this)

    @Serializable
    data class MyModel (val name: String)

    @Test
    fun testJson() {

        val model = MyModel("test")
        val modelJson = model.toModelJson()
        assertTrue(modelJson.isNotEmpty())

        val genericJson = model.toJson()
        assertTrue(genericJson.isNotEmpty())
    }
}
Exception thrown:
kotlinx.serialization.SerializationException: Serializer for class 'Any' is not found.
m
It might work if you do an inline/reified variant of the method instead, so the type is known:
Copy code
inline fun <reified T> T.toJson(): String = serializer.encodeToString(this)
This would still fail on runtime if T is not
@Serializable
Btw I don't think you need the contextual configuration of your serializer, as long as all the classes you use are
@Serializable
👍 1
c
yeah thanks - I ended up doing something similar to this.