What is your use-case and why do you need this feature?
Ability to parse nullable properties when the keys are not present in the JSON.
@kotlinx.serialization.Serializable
data class Foo(val foo: String?)
Trying to parse this JSON string {} fails.
The current workaround would be to add a default value val foo: String? = null. However, we don't always have access to the entities in order to apply the fix. One example is when trying to create external serializers for the SqlDelight autogenerated entities.
Describe the solution you'd like
Add a configuration acceptNonPresentKeys which when set to true, the parser would automatically produce
Foo(foo = null) when {} this is provided.
Adding a default value is not a workaround, it is a way to explicitly configure what to do when the property is missing (what default value to use) and to ensure that its usage from code is as close as possible from deserialization to avoid any confusion.
For a case of SqlDelight auto-generated entities, IMHO, a better fix would be to make SqlDelight configurable so that it generates entities with appropriate default values and also marks them as @Seralizable, even further reducing boilerplate (no need to write external serializers).
I totally understand that this request might make things less clear but isn't this feature supported on other platforms?
Regarding the SqlDelight use case, unfortunately it is not that straightforward when using column adapters with default values.
Resurfacing this issue again
I also just got bit by the same problem while trying to migrate from Moshi to kotlinx.serialization
I had nullable properties that I expected to be initialized with null if the value is ever missing from the API, but instead, the app just crashed
I believe it would be really nice to provide this option as an opt-in configuration, so whoever uses it is fully aware and there won't be any confusion. This will also make transition to kotlinx.serialization from other libraries much smoother
I think giving null to nullable property is more reasonable than crashing app due to missing property.
How about adding a configuration something like below?
JsonConfiguration(nullableAsOptional = true)
Most helpful comment
Resurfacing this issue again
I also just got bit by the same problem while trying to migrate from Moshi to kotlinx.serialization
I had nullable properties that I expected to be initialized with
nullif the value is ever missing from the API, but instead, the app just crashedI believe it would be really nice to provide this option as an opt-in configuration, so whoever uses it is fully aware and there won't be any confusion. This will also make transition to kotlinx.serialization from other libraries much smoother