JsonSerializerOptions copy constructor includes JsonSerializerContext

With the release of source generation in .NET 6, the JsonSerializerOptions copy constructor was intentionally made to ignore its JsonSerializerContext state. This made sense at the time since JsonSerializerContext was designed to have a 1:1 relationship with JsonSerializerOptions instances. In .NET 7, IJsonTypeInfoResolver replaces JsonSerializerContext to generalize the context, which removes the need for tight coupling between JsonSerializerOptions and JsonSerializerContext. The copy constructor now includes the IJsonTypeInfoResolver/JsonSerializerContext information, which could manifest as a breaking change for some scenarios.

Previous behavior

In .NET 6, the following code serializes successfully. The MyContext configuration (which doesn't support Poco2) is discarded by the copy constructor, and serialization succeeds because the new options instance defaults to using reflection-based serialization.

var options = new JsonSerializerOptions(MyContext.Default.Options);
JsonSerializer.Serialize(new Poco2(), options);

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

public class Poco1 {}
public class Poco2 {}

New behavior

Starting in .NET 7, the same code as shown in the Previous behavior section throws an InvalidOperationException. That's because the copy constructor now incorporates MyContext metadata, which doesn't support Poco2 contracts.

Version introduced

.NET 7

Type of breaking change

This change can affect binary compatibility.

Reason for change

JsonSerializerContext was the only setting ignored by the copy constructor. This behavior was surprising for some users.

If you depend on the .NET 6 behavior, you can manually unset the TypeInfoResolver property to get back reflection-based contract resolution:

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

Affected APIs