Tarmil / FSharp.SystemTextJson

System.Text.Json extensions for F# types
MIT License
323 stars 44 forks source link

Allowing null fields example from the docs is not working #186

Open paredes-intracen opened 1 month ago

paredes-intracen commented 1 month ago

I was doing some tests to integrate deserialization into my code base, and I've been looking into the scenario with unspecified fields in the JSON. Which led me to the docs here https://github.com/Tarmil/FSharp.SystemTextJson/blob/master/docs/Customizing.md#allowing-null-fields

But running the example from the docs throws the exception "System.Text.Json.JsonException: Missing field for record type Rectangle: bottomLeft", regardless if the WithAllowNullFields() is used or not.

I ran the example with a FSX script and the #r "nuget: FSharp.SystemTextJson" package reference syntax.

I also posted a question in StackOverflow with a sightly modified example (what I'm really after is to be able to deserialized unspecified JSON fields into an Option type), and thanks to that I found another person who also confirmed that the example is not working as-is.

Tarmil commented 1 month ago

Hmm, I can see how that bit of the documentation can be misleading. What it says is that in the case where the field's type is a class (not an option), then AllowNullFields will allow it to be null. If you want to allow None to represent a missing field, then what you need is:

.WithSkippableOptionFields(SkippableOptionFields.Always)

Or if you want both absence and null to be deserialized as None:

.WithSkippableOptionFields(SkippableOptionFields.Always, deserializeNullAsNone = true)
paredes-intracen commented 1 month ago

Thanks so much, definitely what I was after is this:

.WithSkippableOptionFields(SkippableOptionFields.Always, deserializeNullAsNone = true)

Now, I may be wrong, but I still think there is something about the example for WithAllowNullFields(). The deserialization never succeeds in my tests.

Thanks again.