Skip to content

[#151] Add option to deserialize both null and missing as None#184

Merged
Tarmil merged 1 commit intomasterfrom
deserialize-null-as-none
Apr 4, 2024
Merged

[#151] Add option to deserialize both null and missing as None#184
Tarmil merged 1 commit intomasterfrom
deserialize-null-as-none

Conversation

@Tarmil
Copy link
Owner

@Tarmil Tarmil commented Apr 3, 2024

Add optional argument deserializeNullAsNone: bool to option .WithSkippableOptionFields(SkippableOptionFields).

let options =
    JsonFSharpOptions.Default()
        .WithSkippableOptionFields(SkippableOptionFields.Always, deserializeNullAsNone = true)
        .ToJsonSerializerOptions()

JsonSerializer.Deserialize<{| x: int option|}>("""{}""", options)
// --> {| x = None |}

JsonSerializer.Deserialize<{| x: int option|}>("""{"x":null}""", options)
// --> {| x = None |}

Compare with the current, and now default false behavior:

let options =
    JsonFSharpOptions.Default()
        .WithSkippableOptionFields(SkippableOptionFields.Always)
        .ToJsonSerializerOptions()

JsonSerializer.Deserialize<{| x: int option|}>("""{}""", options)
// --> {| x = None |}

JsonSerializer.Deserialize<{| x: int option|}>("""{"x":null}""", options)
// JsonException: The JSON value could not be converted to System.Int32.

Fixes #151, #176, #182.

Note: I have changed my mind since this comment, in that this setting only affect option and voption, but not Skippable. The reason is that Skippable exists precisely for fields that must be skipped, and so that Skippable<T option> can be used to explicitly distinguish between missing and null. This ability should be usable alongside option values that can be deserialized from either null or missing.

@Tarmil Tarmil added the enhancement New feature or request label Apr 3, 2024
@Tarmil Tarmil merged commit 498f7a5 into master Apr 4, 2024
@Tarmil Tarmil deleted the deserialize-null-as-none branch April 4, 2024 09:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Inconsistent behavior of nulls?

1 participant