Tarmil / FSharp.SystemTextJson

System.Text.Json extensions for F# types
MIT License
329 stars 45 forks source link

Version 1.0 lost the ability to interpret missing field as None #134

Closed geysernrd closed 1 year ago

geysernrd commented 1 year ago

In prior versions, this dummy example would result in "testThing" being set to a "Thing" with "stringOption" equal to None:

type Thing = { stringOption : string option; }
let testThing = JsonSerializer.Deserialize("{ }", typeof<Thing>, options) :?> Thing

In v1.0, this error occurs instead: "System.Text.Json.JsonException: Missing field for record type FSI_0006+Thing: stringOption"

Granted, I can see a debate between interpreting missing data as "None" vs. interpreting it as malformed data. But a big reason I chose SystemTextJson for my use case was the ability to rapidly respond to website feature additions with new optional data fields, without having to manually edit serialized production JSON. In other words, this is a showstopper.

If the change was intentional, might it be possible to reintroduce interpreting a missing value as "None"; e.g., as a non-default option? (Apologies if this already exists; I didn't see it in the documentation. Based on the description of the allowNullFields attribute, it seems like the code above still ought to work, regardless of how allowNullFields is set.)

Tarmil commented 1 year ago

This is indeed an intentional change, see the release notes. You can support your use case by setting DefaultIgnoreCondition = WhenWritingNull on your JsonSerializerOptions.

I'll look into updating the documentation for allowNullFields accordingly.

geysernrd commented 1 year ago

Got it, thanks @Tarmil!