Tarmil / FSharp.SystemTextJson

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

Can't parse Option<'T> from a json field that's either missing or null #182

Closed pkese closed 3 months ago

pkese commented 3 months ago

What's the required set of options that gets the following code to work?

Either I'm getting: Missing field for record type
or The JSON value could not be converted to System.Double. Cannot get the value of a token type 'Null' as a number.

#r "nuget: FSharp.SystemTextJson, 1.2.42"
open System.Text.Json
open System.Text.Json.Serialization

let options =
    JsonFSharpOptions.Default()
        // Add any .WithXXX() calls here to customize the format
        .WithSkippableOptionFields()
        .WithAllowNullFields()
        //.WithUnwrapOption()
        .ToJsonSerializerOptions()

type Doc = { x: float option }

let json = """
    [
        {"x": 1.0},
        {"x": 2},
        {"x": null},
        {}
    ]
"""

JsonSerializer.Deserialize<Doc[]>(json, options)
|> printfn "%A"
pkese commented 3 months ago

Note: The above example is just a minimal reproduction that I extracted from a real world sample,
i.e. I'm dealing with a REST API, that returns some properties as nulls while other properties get omitted from response.

Tarmil commented 3 months ago

This is released in v1.3.13:

JsonFSharpOptions.Default()
    .WithSkippableOptionFields(SkippableOptionFields.Always, deserializeNullAsNone = true)
pkese commented 3 months ago

Thank you @Tarmil. I highly appreciate your effort.