Mehmet
03/07/2025, 9:11 AMBoolean
, without requiring explicit @Contextual
annotations on every field?Mehmet
03/07/2025, 9:14 AMGson
and need to handle diverse Boolean
representations (e.g., `true`/`false`, `"true"`/`"false"`, `1`/`0`, `"1"`/`"0"`, `1.0`/`0.0`) due to legacy backend inconsistencies.
I’ve created a custom KSerializer
for Boolean
and registered it as a contextual serializer in my Json
instance:
private val json: Json = Json {
serializersModule = SerializersModule {
contextual(Boolean::class, MyCustomBooleanSerializer())
}
}
However, Boolean fields are still deserialized using the default built-in serializer unless I explicitly annotate them with @Contextual
. It appears that contextual serializers are only resolved when a built-in serializer is not found (as seen in SerializersModule.reflectiveOrContextual).
Is there a way to prioritize my custom serializer over the built-in one for all instances of Boolean
, without requiring per-field annotations? Or, is there any other approach to achieve global overriding of built-in serializers for primitive types?Mehmet
03/07/2025, 9:21 AMJson
instance :
class MyCustomBooleanSerializer : KSerializer<Boolean> {
// ... custom deserialization logic to handle "1", "0", "true", "false", etc.
}
val json = Json {serializersModule = SerializersModule { contextual( MyCustomBooleanSerializer()) }
@Serializable data class MyData(val value: Boolean)
I expect this deserialization to work:
json.decodeFromString<MyData>("""{"value": "1"}""")
however, it fails with
kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 11: Expected valid boolean literal prefix, but had '1' at path: $.value
JSON input: {"value": 1}
if I annotate the value with @Contextual
it works as expected:
@Serializable data class MyData( @Contextual val value: Boolean)
ephemient
03/07/2025, 2:35 PMJsonConfiguration.isLenient
mode)rnett
03/08/2025, 12:47 AMMehmet
03/10/2025, 3:06 PMI’ve had to create custom encoders that delegate everything but the type I care about to the base encoder I want to use.@rnett that will work for me too. how can I write my custom encoder/decoder? I couldn’t see anything about that in docs
rnett
03/10/2025, 7:18 PMMehmet
03/11/2025, 7:31 AM