Closed
Description
I have the following method and I have my class which is generated. For the generated class I have a self-written serializer that is connected to the SerializersModule. I need both the Serializable annotation, i.e. the generated serializer and the custom serializer. How can I implement a function from Json to use the serializer from the module. Thanks in advance
public class JsonElementConverter(
private val json: Json,
) {
public fun <T : Any> fromJson(element: JsonElement, type: KType): T {
return json.decodeFromJsonElement(json.serializersModule.serializer(type) as KSerializer<T>, element)
}
}
@Serializable
public data class CustomObject(
val field1: String,
val field2: String,
)
public object CustomObjectSerializer : KSerializer<CustomObject> {
override val descriptor: SerialDescriptor
get() = TODO("Not yet implemented")
override fun deserialize(decoder: Decoder): CustomObject {
TODO("Not yet implemented")
}
override fun serialize(encoder: Encoder, value: CustomObject) {
TODO("Not yet implemented")
}
}
public fun main() {
val json = Json {
serializersModule = SerializersModule {
contextual(CustomObject::class, CustomObjectSerializer)
}
}
val jsonElementConverter = JsonElementConverter(json)
val jsonElement = buildJsonArray {
add(buildJsonArray {
add(buildJsonObject {
put("field1", JsonPrimitive("field1"))
put("field2", JsonPrimitive("field2"))
})
})
}
val type = typeOf<List<List<CustomObject>>>()
val result = jsonElementConverter.fromJson<List<List<CustomObject>>>(jsonElement, type)
println(result)
}