Skip to content

Obsolete JsonSerializerOptions.AddContext #83280

Closed
@eiriktsarpalis

Description

@eiriktsarpalis

Background & Motivation

The JsonSerializerOptions.AddContext<TContext>() method was introduced in .NET 6 as a means to associate JsonSerializerOptions instances with a given JsonSerializerContext type. This method was largely superseded in .NET 7 with the introduction of contract customization and the JsonSerializerOptions.TypeInfoResolver property.

We should obsolete AddContext for the following reasons:

  1. Contrary to what the name suggests, it replaces user configuration instead of appending to it.
  2. It can be confused with the new JsonSerializerOptions.TypeInfoResolverChain when manipulating resolver chains.
  3. The method only works with JsonSerializerContext type parameters, not with arbitrary IJsonTypeInfoResolver instances.
  4. The method freezes the JsonSerializerOptions for further modification:
    JsonSerializerOptions options = new();
    options.AddContext<Context1>(); // success
    options.AddContext<Context2>(); // InvalidOperationException

API Proposal

public class JsonSerializerOptions
{
     [Obsolete(/* SYLIB code TBD? */)]
     public void AddContext<TContext>() : where TContext : JsonSerializerContext { }
}

cc @eerhardt

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions