Home > Software design >  How to (de)serialize an instance of a generated data class
How to (de)serialize an instance of a generated data class

Time:06-23

I need to (de)serialize to and from JSON some of the data classes that are generated by a Gradle plugin. Normally I would just use a library like Moshi or kotlinx.serialization and add the proper annotation to the class I want to serialize but, since this data classes are autogenerated, this is a problem.

I would like to avoid manually to map all the fields of the generated data class to some other class that I can (de)serialize, or to write a custom adapter for all these data class so, I was wondering if there is another way to tell, for example, kotlinx.serialization that a class is @Serializable without having to put the annotation directly on top of the class itself.

Or, alternatively, is there a better way to convert to and from a string an instance of a generated data class?

CodePudding user response:

kotlinx.serialization supports generating serializers for 3rd party classes. We need to use forClass parameter in @Serializer, for example:

data class MyData(val data: String)

@Serializer(forClass = MyData::class)
object MyDataSerializer

fun main() {
    val data = MyData("foo")
    println(Json.encodeToString(MyDataSerializer, data))
}

You can read more in the official documentation: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#deriving-external-serializer-for-another-kotlin-class-experimental

  • Related