-
Notifications
You must be signed in to change notification settings - Fork 643
Getting serializer from contextual given only KType #2967
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Do you need something like |
For annotation |
@eduard1abdulmanov123 If you are generating models, you would also have generated serializers (either by generating the proper Kotlin source, or just generating a serializer yourself). But note that kotlinx.serialization is a compile time system. It doesn't support reflection based serialization itself (if you create a way to get correct serializers then the library/formats would not know the difference) |
But if we consider the issue a little differently. For example, we have a 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)
}
} |
Your code sample could directly ask the contextual serializer from the serializersModule, but you do need to keep in mind that this would not work for member types directly. There is really only one way to reliably adjust the serializers used for specific types. That is to have a format that replaces the serializer used as appropriate. You would thus have to create a format that wraps Json (in this case) and replaces the serializer/deserializer as appropriate. |
@eduard1abdulmanov123 Effectively yes, in your encoder/decoders (with your format) you need to override |
Thank you very much for your answers! |
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
The text was updated successfully, but these errors were encountered: