Tarmil / FSharp.SystemTextJson

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

Regression in 1.2: NullReferenceException when serializing null record field #172

Closed cmeeren closed 1 year ago

cmeeren commented 1 year ago

Repro:

open System
open System.Text.Json
open System.Text.Json.Serialization

type X = { X: X }

let x = { X = Unchecked.defaultof<_> }

let options = JsonSerializerOptions()
options.Converters.Add(JsonFSharpOptions.Default() |> JsonFSharpConverter)

Console.WriteLine(JsonSerializer.Serialize(x, options))

On v1.1 this works fine, but on v1.2 this throws:

System.NullReferenceException: Object reference not set to an instance of an object.
   at lambda_method2(Closure, Object)
   at System.Text.Json.Serialization.JsonRecordConverter`1.WriteRestOfObject(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonRecordConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCoreAsObject(Utf8JsonWriter writer, Object value, JsonTypeInfo jsonTypeInfo)
   at System.Text.Json.Serialization.JsonRecordConverter`1.WriteRestOfObject(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonRecordConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
   at System.Text.Json.Serialization.JsonConverter`1.TryWrite(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.Serialization.JsonConverter`1.WriteCore(Utf8JsonWriter writer, T& value, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteCore[TValue](Utf8JsonWriter writer, TValue& value, JsonTypeInfo`1 jsonTypeInfo)
   at System.Text.Json.JsonSerializer.WriteString[TValue](TValue& value, JsonTypeInfo`1 jsonTypeInfo)
   at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)
   at <StartupCode$Test2>.$Program.main@() in \_\Test2\Test2\Program.fs:line 12
cmeeren commented 1 year ago

I have identified the commit this bug was introduced as 8ab76c9ad000d3db1b59b1ed892dce0b7147a8fc. This only enabled the flag HandleNull in Record.fs, so it's something about the code invoked when using that flag.

Tarmil commented 1 year ago

Fixed in v1.2.42, thanks for the PR!

cmeeren commented 1 year ago

Excellent, thanks a lot!