Skip to content

Support using any dictionary as JsonExtensionData #31645

Description

@kostrse

IMHO, IReadOnlyDictionary should work identical to IDictionary when using with JsonExtensionData attribute.

[JsonExtensionData]
public IReadOnlyDictionary<string, JsonElement> Payload { get; set; }

Currently it fails with error:

System.InvalidOperationException: The data extension property 'Payload' does not match the required signature of IDictionary<string, JsonElement> or IDictionary<string, object>.

This is analogous to collection properties which can be defined as List<T>, IList<T> or IReadOnlyList<T> etc.

Activity

  1. changed the title [-]Support IReadOnlyDictionty with JsonExtensionData[/-] [+]Support IReadOnlyDictionary with JsonExtensionData[/+] on Feb 3, 2020
  2. added
    untriaged
    on Feb 3, 2020
  3. added this to the 5.0 milestone on Feb 21, 2020
  4. added
    enhancement
    and removed
    untriaged
    on Feb 21, 2020
  5. layomia commented on Feb 21, 2020

    @layomia
    Contributor

    Triage: we should generalize this to support all dictionary types that the serializer supports as extension data. Supported types can be found here dotnet/docs#15807 (comment).

    Changing the title to reflect this.

  6. changed the title [-]Support IReadOnlyDictionary with JsonExtensionData[/-] [+]Support using any dictionary as JsonExtensionData[/+] on Feb 21, 2020
  7. layomia commented on Feb 21, 2020

    @layomia
    Contributor

    Adding request for ImmutableDictionary from @mwikstrom in #32408:

    Hi,

    I want to use an immutable dictionary to store json extension data.

    I tried to see if this is supported by writing the following test in an mstest project targeting netcoreapp3.1:

    [TestClass]
    public sealed class JsonExtensionDataTest
    {
        class HasImmutableExtensionData
        {
            [JsonExtensionData]
            public ImmutableDictionary<string, JsonElement> ExtensionData { get; set; }
        }
    
        [TestMethod]
        public void Can_deserialize_immutable_extension_data()
        {
            const string json = "{\"foo\":123}";
            var obj = JsonSerializer.Deserialize<HasImmutableExtensionData>(json);
            Assert.IsNotNull(obj.ExtensionData);
            Assert.IsTrue(obj.ExtensionData.ContainsKey("foo"));
        }
    }

    That test fails with a NullReferenceException which surprised me:

     Can_deserialize_immutable_extension_data
       Source: JsonExtensionDataTest.cs line 42
       Duration: 39 ms
    
      Message: 
        Test method JsonExtensionDataTest.JsonExtensionDataTest.Can_deserialize_immutable_extension_data threw exception: 
        System.NullReferenceException: Object reference not set to an instance of an object.
      Stack Trace: 
        JsonSerializer.CreateDataExtensionProperty(JsonPropertyInfo jsonPropertyInfo, ReadStack& state)
        JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
        JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, Utf8JsonReader& reader)
        JsonSerializer.Deserialize(String json, Type returnType, JsonSerializerOptions options)
        JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
        JsonExtensionDataTest.Can_deserialize_immutable_extension_data() line 45
    

    I consider the experienced behavior a bug. Another exception should have been thrown.

    I would also like to request future support for using ImmutableDictionary<TKey, TValue> as backer for [JsonExtensionData].

  8. added
    help wanted
    on Mar 26, 2020
  9. Romanx commented on Apr 6, 2020

    @Romanx

    Hey there,

    I'd love to pick this up and take a look at getting these types serializing. Could the issue be assigned to me?

  10. layomia commented on Apr 7, 2020

    @layomia
    Contributor

    @Romanx, certainly. Please let me know if you run into any issue or have any questions.

  11. removed
    help wanted
    on Apr 7, 2020
  12. Romanx commented on Apr 7, 2020

    @Romanx

    @layomia I can't seem to get the project to build.

    I've forked and cloned the repo, built everything following this. when I opened vs using build -vs System.Text.Json but i'm getting errors in the ref project about Project System.Memory is not compatible with netcoreapp5.0.

    If i unload that project then I get get everything to build but i can't seem to get the tests to run and looking in the test output from VS i'm seeing
    None of the specified source(s) 'C:\Projects\dotnet-runtime\artifacts\bin\System.Text.Json.Tests\Debug\System.Text.Json.Tests.dll' is valid. Fix the above errors/warnings and then try again.

    Following that path i find that my output is being put into a folder netcoreapp5.0-Debug so prefixed with the TFM.

    I may be being dense and have missed something obvious but any help would be appreciated for a first timer!

  13. 13 remaining items

  14. Romanx commented on Jan 27, 2023

    @Romanx

    No problem removing me from this @krwq. After the PR got closed I didn't go back to taking a look at this but good to know there may be hope for this yet! :)

  15. added
    in-pr
    on Oct 11, 2025
  16. Romanx commented on Oct 12, 2025

    @Romanx

    @stephentoub If work is being done on this again I'd be happy to try help rather than using copilot but that up to you.

    My original code worked but had some perf regressions that were weren't sure about. It also didn't hand the source generator usecase.

  17. stephentoub commented on Oct 18, 2025

    @stephentoub
    Member

    IReadOnlyDictionary support was added as was originally requested. Other types like Immutable Dictionary are still not allowed.

  18. removed
    in-pr
    on Jan 3, 2026
  19. TonyValenti commented on Jan 12, 2026

    @TonyValenti

    Hi @stephentoub -
    I'd really like to have JsonExtensionData support ImmutableDictionary<string, JsonElement>. Hopefully this makes it to .net 11!

  20. stephentoub commented on Jan 12, 2026

    @stephentoub
    Member

    I'd really like to have JsonExtensionData support ImmutableDictionary<string, JsonElement>

    why?

  21. TonyValenti commented on Jan 12, 2026

    @TonyValenti

    In all of our JSON-based objects, we use records and immutable collections to enforce that the objects cannot be modified in any way. While using an IReadOnlyDictionary might allow us to do that, we then lose all the niceness of working with the Immutables.

  22. stephentoub commented on Jan 12, 2026

    @stephentoub
    Member

    In all of our JSON-based objects, we use records and immutable collections to enforce that the objects cannot be modified in any way. While using an IReadOnlyDictionary might allow us to do that, we then lose all the niceness of working with the Immutables.

    You're taking a really big performance hit using ImmutableDictionary. You really don't want it for this scenario (and most scenarios). See my explanation at https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-8/#frozen-collections.

  23. TonyValenti commented on Jan 13, 2026

    @TonyValenti

    Hi @stephentoub -
    When working with JSON, what is considered the "right" collection types to ensure immutability?

    The approach we have been taking is as follows:

    • Base classes must all inherit from records
    • For collections, use ImmutableArray<T>?
    • For dictionaries, use ImmutableDictionary<string, T>?

    We looked at ImmutableList but found the performance wasn't right.
    We considered FrozenDictionary but it didn't seem to be json compatible at the home.
    Whatever we use, we want to have one, simple story to tell our JSON team.

  24. stephentoub commented on Jan 14, 2026

    @stephentoub
    Member

    We considered FrozenDictionary but it didn't seem to be json compatible at the home.

    I'm not sure what that means?

    For dictionaries, use ImmutableDictionary<string, T>?

    In general, you can use IReadOnlyDictionary<> and treat the concrete implementation as an implementation detail. If you don't care about downcasting, you can use Dictionary<>. If you do, you can use ReadOnlyDictionary<> around a Dictionary<>. For something that's transient, that's your best option. For something that's going to be around for a while and that'll be read from over and over again, consider FrozenDictionary<>. ImmutableDictionary<> is almost never what you want.

  25. jasoncouture commented on May 12, 2026

    @jasoncouture

    ImmutableDictionary<> is almost never what you want.

    It's your opinion, not what people do or don't want.
    I definitely DO want this, and so do others, for good reasoning:

    It's a perfectly valid use case to shove some more stuff in there: with { ExtensionData = obj.ExtensionData.Add() };

    Don't get me wrong, I'm not saying you SHOULDN'T use FrozenDictionary<>, but this is a pain point for enough people that it's a warranted feature.

    The current state leaves me with some options, none of which are good:
    Give up my immutable objects (Not going to happen)
    Use FrozenDictionary (Creation overhead, and further mutations via re-construction is a problem.)
    Write my own converter, which either requires reflection, or naming all of the known properties (READ: Breaks constantly, and in non-obvious ways).
    Create duplicate objects, just for serailization, and map to/from them (Creating objects for no reason).

    Not to mention, in my experience, this data is either not touched at all, and just used to transit data, or is touched once, or a handful of times.
    The creation time for frozen dictionary far exceeds 90% of "slow" lookups from ImmutableDictionary, in those cases. It's not until the object is massive that you gain actual benefit here. (Or very frequently read, not sure how many lookups are required to break even, but I'm willing to bet >= 100)

    EDIT: I stand corrected, that appears to be fixed, though the memory hit is still not great.

    Benchmark result
    BenchmarkDotNet v0.14.0, Fedora Linux 43 (KDE Plasma Desktop Edition)
    AMD Ryzen 9 7940HS w/ Radeon 780M Graphics, 1 CPU, 16 logical and 8 physical cores
    .NET SDK 10.0.103
      [Host]     : .NET 10.0.3 (10.0.326.7603), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
      DefaultJob : .NET 10.0.3 (10.0.326.7603), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI
    
    
    | Method                            | N    | Mean         | Error       | StdDev      | Gen0    | Gen1   | Allocated |
    |---------------------------------- |----- |-------------:|------------:|------------:|--------:|-------:|----------:|
    | FrozenDictionary_CreateAndRead    | 5    |     186.8 ns |     3.28 ns |     3.07 ns |  0.0725 |      - |     608 B |
    | ImmutableDictionary_CreateAndRead | 5    |     259.8 ns |     1.25 ns |     1.11 ns |  0.0563 |      - |     472 B |
    | FrozenDictionary_CreateAndRead    | 50   |   3,138.6 ns |    47.78 ns |    37.31 ns |  0.9346 |      - |    7824 B |
    | ImmutableDictionary_CreateAndRead | 50   |   3,974.5 ns |    13.31 ns |    12.45 ns |  0.4044 |      - |    3392 B |
    | FrozenDictionary_CreateAndRead    | 100  |   6,325.3 ns |    80.31 ns |    75.12 ns |  1.8234 | 0.0610 |   15288 B |
    | ImmutableDictionary_CreateAndRead | 100  |   8,183.6 ns |    23.13 ns |    20.50 ns |  0.7782 | 0.0153 |    6592 B |
    | FrozenDictionary_CreateAndRead    | 1000 |  67,038.4 ns | 1,092.91 ns | 1,022.31 ns | 15.3809 | 1.9531 |  129672 B |
    | ImmutableDictionary_CreateAndRead | 1000 | 117,426.2 ns |   546.18 ns |   510.90 ns |  7.5684 | 1.4648 |   64192 B |
    
    Benchmark code
    using System.Collections.Frozen;
    using System.Collections.Immutable;
    
    BenchmarkRunner.Run<DictionaryBenchmark>();
    
    [MemoryDiagnoser]
    public class DictionaryBenchmark
    {
        [Params(5, 50, 100, 1000)]
        public int N { get; set; }
    
        private string[] _keys = null!;
    
        [GlobalSetup]
        public void Setup()
        {
            _keys = Enumerable
                .Range(0, N)
                .Select(i => $"key_{i}")
                .ToArray();
        }
    
        [Benchmark]
        public int FrozenDictionary_CreateAndRead()
        {
            var dict = _keys.ToFrozenDictionary(k => k, k => k);
            int sum = 0;
            foreach (var key in _keys)
            {
                sum += dict[key].Length;
            }
            return sum;
        }
    
        [Benchmark]
        public int ImmutableDictionary_CreateAndRead()
        {
            var dict = _keys.ToImmutableDictionary(k => k, k => k);
            int sum = 0;
            foreach (var key in _keys)
            {
                sum += dict[key].Length;
            }
            return sum;
        }
    }

    What NOT supporting this does, is either force a micro-optimization (That is often not an optimization at all), or make things mutable.

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

Metadata

Metadata

Assignees

Labels

area-System.Text.Jsonenhancementhelp wantedwishlist

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions