Hey would it be possible to create some sort of "o...
# serialization
f
Hey would it be possible to create some sort of "optional" serializer? E.g. Some generic type that can have 3 states (unset; set but null; set with value) and in case the generic type indicates its unset I don't want to include it in the serialization output?
g
Looks that you need some wrapper class for this to represent unset behaviour (like Optional<T?>) and write a custom serializer for it
f
Yes exactly. But can a custom serializer for
Optional<T?>
decide to omit a field? or will it always write that field?
g
I believe yes, you call
serialize/encode
manually, so you can just do not write anyting, never tried though
f
Hmm does not work unfortunately. I tried the following Code:
Copy code
class ValueSerializer <T> (private val dataSerializer: KSerializer<T>) : KSerializer<Value<T>> {
    override val descriptor: SerialDescriptor = dataSerializer.descriptor

    override fun serialize(encoder: Encoder, value: Value<T>) {
        if (value.isSet) {
            if (value.value == null) {
                encoder.encodeNull()
            } else {
                dataSerializer.serialize(encoder, value.value!!)
            }
        }
    }
    override fun deserialize(decoder: Decoder) = TODO("Not implemented!")
}
But when running
Copy code
val testObject = TestClass()
    testObject.value1.value = "Hello World"
    testObject.value3.value = null

    println(Json.encodeToString(testObject))
The output is
{"value1":"Hello World","value2":,"value3":null}
g
hmm, yeah, it probably about JsonSerializer itself
f
It's a very unique problem but would be cool if someone has an idea how I could do this
g
I think all logic about skipping values is baked to json serializer itself
so encoder will not help here
because it just encodes value, but it should be a part of serializer itself I believe
but unclear how to make it work per type
f
yeah that would be the important component to have a generic system
Like my main idea behind this is to have a simple "patch" system where I can ether not update a value or I can explicit set a value to Null
and it would be cool if I can use this to create a JSON to be send to a server but also to receive on the server and put back into a object
k
I am wondering, that would mean that your request class would be full of this wrappers right?
v
Maybe if you have a special "this is unset" marker value, then set this as default value and configure the JSON serializer to not encode default values.
f
@kqr yes that is correct my request class would instead of String always have my OptionalValue<String> as data type for example. But its a small price to pay if I don’t have to work with basic JsonObject trees as I still get data safety etc. In that regards Javascript can be useful as you have
undefined
and
null
that you can use for that.