hi all, i have a somewhat complex use case for ser...
# serialization
t
hi all, i have a somewhat complex use case for serialization for messages being communicated around a distributed system. The messages come in like so:
Copy code
{
	"sessionId": "...",
	"commandId": "...",
	"message": { ... }
}
So, at a lower layer of my code, I parse the
sessionId
and the
commandId
using
JsonTreeParser
, and using the same parser I extract
message
as a JsonObject. Later on, whoever needs to use the
message
JsonObject can deserialize to whatever they want using
mapper.readTree
. Now, say I need to serialize back to another format. Specifically:
Copy code
{
	"success": true,
	"message": "...",
	"commandId": "...",
	"payload": { ... }
}
That
payload
field is any custom class which needs to be serializable and passed somehow, but I can't find a way to make it a JsonObject, or write any JsonObject for that matter. I also tried making a generic class with an field of the type of
payload
, but that didn't seem like the right direction. I guess what I'm asking is, how can I create a JsonObject from an instance of a class?
thinking about this some more, I guess I just need a method to create that json tree by hand? and i'm not sure where to start with that
s
JsonTreeMapper
can convert serializable classes to json tree and back
t
yes, that's exactly what i'm trying to use
is the
writeTree
function what i'm looking for?
s
yeah
t
okay. is there some documentation I can read about it? my biggest question is how to pair an object with a String and have it serialize that. I've found some examples using `Pair<String, Int>`(for example), but the type will be generic, and from what i've read in the serialization docs about generics i'll have to write some other logic to make it work. is this the right direction?
s
To serialize generic classes, you need to instantiate correct serializers for it. e.g.
PairSerializer(StringSerializer, IntSerializer)
for
Pair<String, Int>
t
ya i think i'm on to something
could i do something like this (this does not compile yet)
Copy code
fun <T: Any> writePayload(payloadSerializer: SerializationStrategy<T>, obj: T) {
        jsonTree.writeTree(Pair("payload", obj), StringSerializer to payloadSerializer)
    }
that gives me a type mismatch though, but what i'm trying to do is say "i have a serializer for you, please use it"
s
PairSerializer
is a class in internal package, not a pair of serializers 🙂
t
yep i think i got it
just understood how it all works
last step, how would i stringify a JsonTreeMapper
s
You mean
JsonElement -> String
? Just call .toString and you would get a correct JSON.