If I have a custom ```JsonTransformingSerializer&l...
# serialization
s
If I have a custom
Copy code
JsonTransformingSerializer<String>(String.serializer())
How can I add this to a json format, serializer module or whatever so it applies to all
String
in the serialized type ? ie. I want to transform all strings
e
which property serializers are used by a class's serializer is determined when it is built (except in the case of
@Contextual
or polymorphic, in which case it retrieves the serializer from the serializersModule)
tl;dr you can't do it for all strings in a format, you have to use
@Serializable(with = ...) String
at all the use sites
s
Is there any other hook then where I can transform all strings then ? I have browsed most of the json code but everything seems internal. (ie. JsonEncoder, JsonWriter etc.)
e
not easily. a custom format that changes
decodeString
could, but that would break things like polymorphic type discriminators
what are you trying to do?
s
For reasons I need to transform multibyte characters to their "escape" sequence ie. Curaçao -> Cura\u00e7ao
e
ah, you could do that as a post-processing step
s
You mean in-place replacement in the serialized json bytes ?
e
yeah, if you're just replacing non-ASCII characters with escaped variants, you can just do that on the String
it won't change anything about the JSON structure
you could file a feature request for this to be a feature in the JSON format, but I don't think it's a common need
s
Yeah it could work. A bit out of the box and I will have to switch away from the streaming encoder.
Thanks for the response !
a
maybe try a value class.
Copy code
@JvmInline
@Serializable(with = MultibyteStringSerializer::class)
value class MultibyteString(val value: String): CharSequence by value

object MultibyteStringSerializer : KSerializer<MultibyteString> {
   // encode/decode...
}
then you can use MultibyteString instead of String in your DTOs
e
that doesn't really help though. you don't have a way of writing that serializer to produce the desired output
if it performs escaping, the Json format will escape those escapes, resulting in
\\
in the output
a
oh I didn’t realise that was the case. Outputting that sort of raw string should be possible in KxS 1.5, with JsonUnquotedLiteral
e
to be released soon, hopefully