Hello :wave: How can we define optional nullable f...
# serialization
d
Hello 👋 How can we define optional nullable fields so we can distinguish following cases during serialization 1) omitted value 2) explicit
null
3) value set I used a sealed class and custom Jackson deserializer in the past (link) but now I'm looking into serialization and need to support
kotlinx-serialization
. I tried something using custom serializer and "skipping" the encode part when I process an instance of
Undefined
sealed class but that produces me a broken JSON, e.g. given
Copy code
data class Wrapper(val name: OptionalInput<String>)
I end up with
{ "name": }
. Any ideas? I don't see any option to skip element in the
JsonEncoder
c
just wondering what would be an example where it makes sense to distinguish between explicit null and field ommited from an api point of view.
k
Don't know if it "makes sense", but I've had to use APIs that used missing value to mean "this value was never set", and null to mean "this value was set at least once, and now is unset again"... definitely not the cleanest of designs...
j
That's the difference between "null" and "undefined" in other languages 😉. At least one could use these values for
c
ok so if you merge two objects undefined or not present would mean don’t change the value and null would set the value to null
d
re: use case - in GraphQL queries/mutations can accept optional nullable arguments and server can also optionally specify default value that will be applied when it is not specified so given a very basic query (
!
at the end of the type means not-null)
Copy code
type Query {
  foo(bar: String): String!
}
clients could run following •
query { foo }
•
query { foo(bar = null) }
•
query { foo(bar = "baz") }
As a client you could create separate queries for unspecified/specified cases but if you have multiple optional arguments in a query it would mean you would have to create
2^number_arguments
permutations which is not really feasible.
if anyone is looking for solution - in my case I was able to set default value as
Undefined
and then configure
encodeDefaults = false
Ugh so I need to have some fields serialized with defaults and others without :( https://github.com/Kotlin/kotlinx.serialization/issues/1091