Skip to content

Developers should have access to System.Text.Json's default internal converters #63791

Open

Description

@eiriktsarpalis

Background and Motivation

Currently, the default json converters used for objects and collection types are internal to System.Text.Json. The library uses hardcoded conventions to decide what default converters to apply to each type: for instance classes that implement IEnumerable<T> are automatically treated as collections, and classes that implement IAsyncEnumerable<T> can only be handled by the async-only IAsyncEnumerable converter. As of today, System.Text.Json offers no mechanism for users to override this convention, and we have received a number of questions from the community about this issue:

Currently the best available workaround is for users to either reimplement the default converters, or wrap/cast the values into a type that produces the desired serialization contract. At the same time, we offer no mechanism for users to tweak the serialization behaviour of the default converters other than using attribute annotations (to be ameliorated once #63686 has been implemented). Related issues:

Proposal

This story proposes making the default internal converters public, so that users are free to opt in to specific converter strategies for their types. Consider the following example:

public class MyClass : IEnumerable<int>, IAsyncEnumerable<int>
{
}

By default, members of type MyClass are serialized as IAsyncEnumerables. Users can still force IEnumerable semantics if they cast the instance to IEnumerable<int>, however there is currently no way to serialize the type as an object. By exposing the default converter types, we can decorate our type definition with attributes:

[JsonConverter(typeof(JsonObjectConverter))] // serialize as object
// [JsonConverter(typeof(JsonCollectionConverter))] // serialize as collection
// [JsonConverter(typeof(JsonAsyncEnumerableConverter)] // serialize as IAsyncEnumerable
public class MyClass : IEnumerable<int>, IAsyncEnumerable<int>
{
}

Moreover, we should consider exposing parameterization on the converters so that users can configure the contract (for example what #38514 is asking for).

NB we should update the source generator so that relevant JsonPropertyAttribute annotations are recognized and trigger relevant metadata generation, cf. #82001 (comment)

Progress

  • Prototyping work
  • API proposal
  • Implementation & tests
  • Documentation

Activity

  1. added
    User Story
    Priority:2
    Cost:S
    on Jan 14, 2022
  2. added this to the 7.0.0 milestone on Jan 14, 2022
  3. ghost added
    untriaged
    on Jan 14, 2022
  4. removed
    untriaged
    on Jan 14, 2022
  5. asik commented on Mar 31, 2022

    @asik

    Related to #67361 , for me the ideal scenario would be that JsonConverter sees that it's an IEnumerable<T>, sees that it has a constructor that takes in an IEnumerable<T>, and uses that constructor.

  6. eiriktsarpalis commented on Mar 31, 2022

    @eiriktsarpalis
    MemberAuthor

    Related to #67361 , for me the ideal scenario would be that JsonConverter sees that it's an IEnumerable<T>, sees that it has a constructor that takes in an IEnumerable<T>, and uses that constructor.

    Yes, that might be a good convention to honor. Similarly for dictionary types that accept IEnumerable<KeyValuePair<TKey, TValue>> parameters.

  7. eiriktsarpalis commented on Jun 17, 2022

    @eiriktsarpalis
    MemberAuthor

    We likely won't have time to work on this before .NET 7 is done, moving to 8.0.0

  8. modified the milestones: 7.0.0, 8.0.0 on Jun 17, 2022
  9. 1 remaining item

  10. added this to the Future milestone on Jan 23, 2023
  11. removed
    Priority:2
    Cost:S
    on Jan 23, 2023
  12. eiriktsarpalis commented on Jan 23, 2023

    @eiriktsarpalis
    MemberAuthor

    Moving to Future as we won't be able to work on this for 8.0

  13. MooVC commented on Jan 25, 2023

    @MooVC

    What is the suggested workaround in this case? I've a type that wraps an array (private field) that implements IEnumerable of that type. I would like it to be serialised as an object, using a public constructor that accepts an array. The type is intended to be immutable, so it would be counterintuitive to allow for collection overrides e.g. Add.

  14. eiriktsarpalis commented on Jan 25, 2023

    @eiriktsarpalis
    MemberAuthor

    The only workaround for now is authoring a custom converter for the type, unfortunately.

  15. paul-michalik commented on Feb 28, 2023

    @paul-michalik

    What is the suggested workaround in this case? I've a type that wraps an array (private field) that implements IEnumerable of that type. I would like it to be serialised as an object, using a public constructor that accepts an array. The type is intended to be immutable, so it would be counterintuitive to allow for collection overrides e.g. Add.

    I am currently solving this by deriving such types from List<T>. This provides the expected behavior (transparent serialization and deserialization as collection of T) but of course adds some risk if the collection should not be manipulated as, well List<T>. I use this for internal types only, so it is mostly harmless.

    I still do not understand what the problem is with implementing a default deserialization converter for types implementing e.g. ICollection<T>: the documentation says it all, this is exactly how it should behave:

    image

  16. AbakumovAlexandr commented on Dec 19, 2024

    @AbakumovAlexandr

    It will have been 3 years soon since this major limitation being in place. Is there any updates with this?

    Without resolving this one, it's really a non-trivial task to implement even pretty basic requirements, for example, 'Deserialize all empty JSON arrays into nulls instead of empty collections supporting all target .NET collection types'.

  17. eiriktsarpalis commented on Dec 20, 2024

    @eiriktsarpalis
    MemberAuthor

    If there are any updates, they will be first posted on this issue. In the meantime, please continue upvoting the OP so that it can be prioritized in the future.

  18. mirek-rynly commented on May 14, 2025

    @mirek-rynly

    Really looking forward to this. We currently have to resort to fragile reflection to work around this limitation.

  19. EdLichtman commented on Oct 3, 2025

    @EdLichtman

    I'm currently building an auto parser, to convert our key store into a strongly typed object cache and have just run into the same issue, in that I basically have to specify every single available type for conversion or else I can't seem to use the default converters.

    I'm very interested in this improvement.

  20. CodingOctocat commented on Feb 20, 2026

    @CodingOctocat

    Ideally, the serialization program should first serialize MyCollection as a type that does not inherit IEnumerable/IList/ICollection, etc., then append "$Items" :[] at the end to store the collection object.

    public class MyCollcetion : List<Foo>
    {
        [JsonPropertyOrder(100)]
        [JsonPorpertyName("a")]
        public int AProp { get; set;}
    
        [JsonPorpertyName("bProp")]
        public string BProp { get; set;}
    
        [JsonIgnore]
        public int CProp { get; set;}
    }
    {
        "bProp" : "b",
        "a" : 1,
        "$Items" : [ ... ]
    }
  21. CoreDX9 commented on Sep 21, 2026

    @CoreDX9

    If I use a custom converter to convert custom types of implementing IEnumerable<T>, the exported JSON schema is incorrect. This became a significant flaw after Microsoft.AspNetCore.OpenApi became the preferred feature. Supporting the configuration of Enumerable as Object has become an urgent requirement.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Team:LibrariesUser Storyarea-System.Text.Json

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions