Skip to content

Passing generic class with nullable reference type in JsonSerializableAttribute raises CS8620 when used #95083

@JenyaRostov

Description

@JenyaRostov

Description

Take this class

[JsonSerializable(typeof(IDictionary<string, object?>))]
public partial class JsonContextTest : JsonSerializerContext { }

When used like this:

IDictionary<string, object?> d = new Dictionary<string, object?>()
{
    ["A"] = "b",
    ["D"] = 1,
    ["C"] = null
};
var b = JsonContent.Create(d, JsonContextTest.Default.IDictionaryStringObject);

It raises CS8620 Argument of type 'System.Collections.Generic.IDictionary<string,object?>' cannot be used for parameter 'inputValue' of type 'System.Collections.Generic.IDictionary<string,object>?' in 'System.Net.Http.Json.JsonContent.Create<T>' because of differences in the nullability of reference types
Generated code for JsonContextTest:

public global::System.Text.Json.Serialization.Metadata.JsonTypeInfo<global::System.Collections.Generic.IDictionary<string, object>> IDictionaryStringObject

Notice the absence of object?
It does not raise any runtime errors however when using
My colleague is treating all warnings as errors so is there any way to avoid raising CS8620 besides NoWarn?

Reproduction Steps

Create class

[JsonSerializable(typeof(IDictionary<string, object?>))]
public partial class JsonContextTest : JsonSerializerContext { }

Use it

IDictionary<string, object?> d = new Dictionary<string, object?>()
{
    ["A"] = "b",
    ["D"] = 1,
    ["C"] = null
};
var b = JsonContent.Create(d, JsonContextTest.Default.IDictionaryStringObject);

Expected behavior

No warning raised

Actual behavior

CS8620 is raised

Regression?

No response

Known Workarounds

No response

Configuration

.NET 8

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additionssource-generatorIndicates an issue with a source generator feature

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions