Skip to content

Reading a record with a [<JsonIgnore>] field of a value type throws NullReferenceException #217

Open

Description

@xperiandri

Problem

JsonSerializer.Deserialize throws NullReferenceException for a record that has a field of a value type marked with [<JsonIgnore>].

Repro

FSharp.SystemTextJson 1.4.36, .NET 10:

#r "nuget: FSharp.SystemTextJson, 1.4.36"

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

type WithIgnoredInt = { Id : string; [<JsonIgnore>] Count : int; Name : string }

let options = JsonFSharpOptions.Default().ToJsonSerializerOptions ()

JsonSerializer.Deserialize<WithIgnoredInt> ("""{"Id":"1","Name":"n"}""", options)
// System.NullReferenceException: Object reference not set to an instance of an object.

The same record with [<JsonIgnore>] Note : string instead reads fine, and Note is null.

Cause

In Record.fs, defaultFields starts as Array.zeroCreate fieldCount, and only the fields whose DefaultValue is ValueSome get a value. An ignored field of a value type such as int has no default value, so its slot stays null, and the record constructor cannot unbox null to int.

Expected

The record gets the default value of the field type for an ignored field (0 for int), as it already gets null for an ignored field of a reference type.

Context

FSharp.Azure.Cosmos refuses such a field in its graph model until a release of this library reads the record (fsprojects/FSharp.Azure.Cosmos).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions