russhwolf
12/12/2020, 10:46 PM@Serializable
data class Foo(val bar: String = "bar")
and deserialize an empty json object
val foo = Json.decodeFromString(Foo.serializer(), "{}")
then you get Foo("bar")
as output rather than an error or Foo("")
or something else.
Can anyone point to what makes that happen? I want to do something similar for a custom format.
(NB I’m not looking for the encodeDefaults
option. That flag controls whether default values are added to Json output. I’m looking for how default values are inferred when missing from Json input.)pajatopmr
12/13/2020, 5:41 AMJsonTransformingSerializer
has become my best friend for situations where I need to munge Json to get what I want. Copious examples exist on my LSP for Kotlin (lsp4k-sdk) repo with more being added daily.Dominaezzz
12/13/2020, 11:36 AMDominaezzz
12/13/2020, 11:37 AMrusshwolf
12/13/2020, 3:13 PMKSerializer
, for the purposes of writing a custom serialization format. For example, AbstractEncoder
has a method encodeElement()
where you can return false
to ignore an element in your encoded output. But I don’t see an equivalent in AbstractDecoder
to report that something is missing from the input you’re trying to decode.pajatopmr
12/13/2020, 10:09 PMrusshwolf
12/13/2020, 11:30 PMdecodeElementIndex()
if it corresponds to something that’s not present in the data. But I don’t quite have it working yet.russhwolf
12/14/2020, 4:05 AMdecodeElementIndex()
would iterate through every index from 0 to descriptor.elementsCount
. Now, it first checks if descriptor.isElementOptional(index)
returns true and if the value is missing from the data it’s trying to decode. If so, it iterates to the next index.