Hello everyone! Is there an option to force keys t...
# serialization
r
Hello everyone! Is there an option to force keys to be sorted alphabetically before the serialization?
r
Object keys don’t have any order in json
r
I know that, that's why I'm asking if there is a way to ensure they are alphabetically ordered
When dealing with hashing and other cryptographic operations this is important 😁
r
Hashing json strings is wrong by definition
I guess making your own custom serializers for every single model isn’t a solution right
r
I'm not trying to hash the JSON data, but converting it into a bytearray and then hashing it. A custom serializer could be a solution, yeah
r
Then just use
toString()
on the
data class
and hash that?
r
They would not return the same thing. Having to deal with a set of API that I cannot change, I need to get the JSON object with the keys alphabetically sorted, convert it to a byte array and then hash it.
r
I see. Do you need to use
kotlinx.serialization
?
r
Yeah, I'm creating a multiplatform project
r
Ok. Then the solution will be hacky. Custom serializers are the first thing I think about, but depending on the amount of models we’re talking about, it may not be the best idea
s
Well, you can convert data class to
JsonObject
with
toJson
method first and then sort keys in map.
r
@sandwwraith How would I do it? Do you have some example code?
s
@Riccardo Montagnin Just use
toJson
instead of
stringify
. You will get
JsonElement
, checkcast it to
JsonObject
which is a usual map under the hood.
r
ok thank you