Skip to content

JsonSerializerOptions copy constructor should include the metadata resolver #71716

@eiriktsarpalis

Description

@eiriktsarpalis

With the release of source generation in .NET 6 the JsonSerializerOptions copy constructor was intentionally made to ignore its JsonSerializerContext state (see also dotnet/aspnetcore#38720). This made sense at the time since JsonSerializerContext was designed to have a 1:1 relationship with JsonSerializerOptions instances.

The implementation of #63686 generalizes JsonSerializerContext with IJsonTypeInfoResolver, which can be used to generate metadata for parametric JsonSerializerOptions instances. The JsonSerializerContext type and source generator have been retrofitted and now implement IJsonTypeInfoResolver.

This issue proposes that we change the JsonSerializerOptions copy constructor so that it also incorporates the metadata resolver. This can potentially introduce a breaking change for users, for instance:

var options = new JsonSerializerOptions(MyContext.Default.Options);
JsonSerializer.Serialize(new Poco1(), options); // will fail serialization since the cloned options instance preserves `MyContext.Default` as its metadata resolver

[JsonSerializable(typeof(Poco1))]
public partial class MyContext : JsonSerializerContext {}

public class Poco1 {}
public class Poco2 {}

For impacted users the suggested workaround is the following:

var options = new JsonSerializerOptions(MyContext.Default.Options);
options.TypeInfoResolver = null; // unset the `MyContext.Default` as the resolver for the options instance.

Metadata

Metadata

Labels

area-System.Text.Jsonbreaking-changeIssue or PR that represents a breaking API or functional change over a previous release.needs-breaking-change-doc-createdBreaking changes need an issue opened with https://github.com/dotnet/docs/issues/new?template=dotnet

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions