diff --git a/src/FSharp.SystemTextJson/Record.fs b/src/FSharp.SystemTextJson/Record.fs index 9585a43..6927bee 100644 --- a/src/FSharp.SystemTextJson/Record.fs +++ b/src/FSharp.SystemTextJson/Record.fs @@ -27,7 +27,8 @@ type private RecordField let isSkippableType = isSkippableType fsOptions p.PropertyType - let canBeSkipped = ignore || ignoreNullValues options || isSkippableType + let canBeSkipped = + ignore || (ignoreNullValues options && nullValue.IsSome) || isSkippableType let read = let m = p.GetGetMethod() @@ -226,7 +227,7 @@ type JsonRecordConverter<'T> internal (options: JsonSerializerOptions, fsOptions | _ -> reader.Skip() | _ -> () - if requiredFieldCount < minExpectedFieldCount && not (ignoreNullValues options) then + if requiredFieldCount < minExpectedFieldCount then for i in 0 .. fieldCount - 1 do if isNull fields[i] && fieldProps[i].MustBePresent then failf "Missing field for record type %s: %s" recordType.FullName fieldProps[i].Names[0] diff --git a/tests/FSharp.SystemTextJson.Tests/Test.Record.fs b/tests/FSharp.SystemTextJson.Tests/Test.Record.fs index 0b760b0..f5370c8 100644 --- a/tests/FSharp.SystemTextJson.Tests/Test.Record.fs +++ b/tests/FSharp.SystemTextJson.Tests/Test.Record.fs @@ -14,6 +14,16 @@ module NonStruct = let actual = JsonSerializer.Deserialize """{"ax":1,"ay":"b"}""" Assert.Equal({ ax = 1; ay = "b" }, actual) + [] + let ``deserialize empty record with ignore-null-values on`` () = + let options = + JsonSerializerOptions(DefaultIgnoreCondition = Serialization.JsonIgnoreCondition.WhenWritingNull) + try + JsonSerializer.Deserialize("{}", options) |> ignore + with + | :? System.NullReferenceException -> failwith "Unexpected NRE." + | ex when ex.Message.Contains("Missing field for record type") -> () // It's expected to fail since the record requires its fields to be initialized. + [] let ``serialize via explicit converter`` () = let actual = JsonSerializer.Serialize { ax = 1; ay = "b" } @@ -291,10 +301,13 @@ module NonStruct = Assert.Equal("""{"unignoredX":1}""", actual) let ignoreNullOptions = - JsonFSharpOptions().ToJsonSerializerOptions(IgnoreNullValues = true) + JsonFSharpOptions() + .WithAllowNullFields() + .ToJsonSerializerOptions(IgnoreNullValues = true) let newIgnoreNullOptions = JsonFSharpOptions() + .WithAllowNullFields() .ToJsonSerializerOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull) [] @@ -754,10 +767,13 @@ module Struct = Assert.Equal("""{"unignoredX":1}""", actual) let ignoreNullOptions = - JsonFSharpOptions().ToJsonSerializerOptions(IgnoreNullValues = true) + JsonFSharpOptions() + .WithAllowNullFields() + .ToJsonSerializerOptions(IgnoreNullValues = true) let newIgnoreNullOptions = JsonFSharpOptions() + .WithAllowNullFields() .ToJsonSerializerOptions(DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull) []