Chris Ruddell
11/24/2020, 4:34 PM@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:
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.
Mranders
11/25/2020, 8:50 AMinline 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
Chris Ruddell
11/30/2020, 7:00 PM