Skip to content

Obsolete JsonSerializerOptions.AddContext #83280

Closed

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

Activity

  1. ghost added
    untriaged
    on Mar 10, 2023
  2. removed
    untriaged
    on Mar 10, 2023
  3. added this to the 8.0.0 milestone on Mar 10, 2023
  4. added
    api-ready-for-review
    blocking
    on Mar 10, 2023
  5. bartonjs commented on Mar 16, 2023

    @bartonjs
    Member

    Looks good as proposed.

    Confirm with @terrajobst that System.Text.Json should use SYSLIB codes.

  6. added
    api-approved
    and removed
    blocking
    api-ready-for-review
    on Mar 16, 2023
  7. ghost added
    in-pr
    on Mar 28, 2023
  8. added a commit that references this issue on Mar 29, 2023
  9. ghost removed
    in-pr
    on Mar 30, 2023
  10. ghost locked as resolved and limited conversation to collaborators on Apr 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

api-approvedarea-System.Text.Json

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions