Skip to content

Breaking change: ArgumentNullException thrown when null is passed as input type to some JsonSerializer serialize methods #21376

@layomia

Description

@layomia

In .NET Core 3.1 and versions 4.6.0-4.7.2 of the System.Text.Json library, null could be passed as the type argument to various serialization methods on JsonSerializer, if the value to serialize was also null. In .NET 5/version 5.0.0, an ArgumentNullException is thrown if null is passed as the type argument.

Version introduced

.NET 5

Old behavior

In .NET Core 3.1 and versions 4.6.0-4.7.2 of the System.Text.Json library, null could be passed as the type argument to various serialization methods on JsonSerializer, if the value to serialize was also null.

New behavior

In .NET 5/version 5.0.0, an ArgumentNullException is thrown if null is passed as the type argument.

Reason for change

null is not expected as a valid input for the type arguments to the various serialization methods. The change was made to ensure correctness and prevent unexpected bugs.

Recommended action

Ensure that a non-null type argument is passed to applicable serialization methods on JsonSerializer. Strategies include handwriting null for values which are null and their type cannot be determined.

For example,

string json;

object? obj = GetObject();
Type? type = obj?.GetType();

if (obj == null)
{
   json = "null";
}
else
{
    json = JsonSerializer.Serialize(obj, type!);
}

Category

  • ASP.NET Core
  • C#
  • Code analysis
  • Core .NET libraries
  • Cryptography
  • Data
  • Debugger
  • Deployment
  • Globalization
  • Interop
  • JIT
  • LINQ
  • Managed Extensibility Framework (MEF)
  • MSBuild
  • Networking
  • Printing
  • Security
  • Serialization
  • Visual Basic
  • Windows Forms
  • Windows Presentation Foundation (WPF)
  • XML, XSLT

Affected APIs


Issue metadata

  • Issue type: breaking-change

Metadata

Metadata

Assignees

No one assigned

    Labels

    🏁 Release: .NET 5Work items for the .NET 5 releasebreaking-changeIndicates a .NET Core breaking change

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions