https://kotlinlang.org logo
#serialization
Title
# serialization
s

spand

01/16/2023, 12:08 PM
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

ephemient

01/16/2023, 12:11 PM
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

spand

01/16/2023, 12:14 PM
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

ephemient

01/16/2023, 12:15 PM
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

spand

01/16/2023, 12:16 PM
For reasons I need to transform multibyte characters to their "escape" sequence ie. Curaçao -> Cura\u00e7ao
e

ephemient

01/16/2023, 12:17 PM
ah, you could do that as a post-processing step
s

spand

01/16/2023, 12:18 PM
You mean in-place replacement in the serialized json bytes ?
e

ephemient

01/16/2023, 12:21 PM
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

spand

01/16/2023, 12:24 PM
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

Adam S

01/16/2023, 1:24 PM
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

ephemient

01/16/2023, 2:39 PM
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

Adam S

01/16/2023, 2:42 PM
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

ephemient

01/16/2023, 2:51 PM
to be released soon, hopefully
10 Views