Skip to content

System.Text.Json cannot deserialize to IReadOnlySet #91875

@StasJS

Description

@StasJS

Description

Reading through https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/supported-collection-types JsonSerializer.Deserialize will support deserialization to a ton of different collection interfaces.

Strangely, IReadOnlySet is not mentioned at all in the page I linked. Not even to say it's not supported, as some collection types have e.g. LinkedListNode<T>.

When trying to deserialize to an IReadOnlySet, JsonSerializer throws a NotSupportedException

Reproduction Steps

  • Run dotnet new console
  • Write Program.cs
using System.Collections.Immutable;
using System.Text.Json;

// Both of these work as expected
var setResult = JsonSerializer.Deserialize<ISet<int>>("[1]");
var immutableSetResult = JsonSerializer.Deserialize<IImmutableSet<int>>("[1]");

// throws NotSupportedException
JsonSerializer.Deserialize<IReadOnlySet<int>>("[1]");

Expected behavior

JsonSerializer.Deserialize<IReadOnlySet<int>>("[1]"); ought to work, like it does for ISet or other readonly collections e.g. IReadOnlyList.

I would also expect IReadOnlySet to be featured in this page https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/supported-collection-types one way or another.

Actual behavior

JsonSerializer.Deserialize<IReadOnlySet<int>>("[1]"); throws NotSupportedException and completely absent from https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/supported-collection-types

Regression?

Don't know.

Known Workarounds

Use ISet or similar.

Configuration

> dotnet sdk check
Version      Status
------------------------
7.0.400      Up to date.

Microsoft.NETCore.App             7.0.10       Up to date.
Microsoft.WindowsDesktop.App      7.0.10       Up to date.

Windows 11 Pro x64

> [System.Environment]::OSVersion
Platform ServicePack Version      VersionString
-------- ----------- -------      -------------
 Win32NT             10.0.22623.0 Microsoft Windows NT 10.0.22623.0

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additionsin-prThere is an active PR which will close this issue when it is merged

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions