You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Support using any dictionary as JsonExtensionData #31645
area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additionshelp wanted[up-for-grabs] Good issue for external contributorswishlistIssue we would like to prioritize, but we can't commit we will get to it yet
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.
Reacted by Bill Poole, dstarkowski, Shravan Rajinikanth, Chris Donnelly, Niels Swimberghe, swh-pp and joergmetzler
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).
@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!
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! :)
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.
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.
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.
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.
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.
usingSystem.Collections.Frozen;usingSystem.Collections.Immutable;BenchmarkRunner.Run<DictionaryBenchmark>();[MemoryDiagnoser]publicclassDictionaryBenchmark{[Params(5,50,100,1000)]publicintN{get;set;}privatestring[]_keys=null!;[GlobalSetup]publicvoidSetup(){_keys=Enumerable.Range(0,N).Select(i =>$"key_{i}").ToArray();}[Benchmark]publicintFrozenDictionary_CreateAndRead(){vardict=_keys.ToFrozenDictionary(k =>k, k =>k);intsum=0;foreach(varkeyin_keys){sum+=dict[key].Length;}returnsum;}[Benchmark]publicintImmutableDictionary_CreateAndRead(){vardict=_keys.ToImmutableDictionary(k =>k, k =>k);intsum=0;foreach(varkeyin_keys){sum+=dict[key].Length;}returnsum;}}
What NOT supporting this does, is either force a micro-optimization (That is often not an optimization at all), or make things mutable.
area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additionshelp wanted[up-for-grabs] Good issue for external contributorswishlistIssue we would like to prioritize, but we can't commit we will get to it yet
Activity
[-]Support IReadOnlyDictionty with JsonExtensionData[/-][+]Support IReadOnlyDictionary with JsonExtensionData[/+]layomia commentedon Feb 21, 2020
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.
[-]Support IReadOnlyDictionary with JsonExtensionData[/-][+]Support using any dictionary as JsonExtensionData[/+]layomia commentedon Feb 21, 2020
Adding request for ImmutableDictionary from @mwikstrom in #32408:
Romanx commentedon Apr 6, 2020
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?
layomia commentedon Apr 7, 2020
@Romanx, certainly. Please let me know if you run into any issue or have any questions.
Romanx commentedon Apr 7, 2020
@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.Jsonbut i'm getting errors in the ref project aboutProject 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-Debugso 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 remaining items
Romanx commentedon Jan 27, 2023
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! :)
Romanx commentedon Oct 12, 2025
@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.
stephentoub commentedon Oct 18, 2025
IReadOnlyDictionary support was added as was originally requested. Other types like Immutable Dictionary are still not allowed.
TonyValenti commentedon Jan 12, 2026
Hi @stephentoub -
I'd really like to have JsonExtensionData support ImmutableDictionary<string, JsonElement>. Hopefully this makes it to .net 11!
stephentoub commentedon Jan 12, 2026
why?
TonyValenti commentedon Jan 12, 2026
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.
stephentoub commentedon Jan 12, 2026
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.
TonyValenti commentedon Jan 13, 2026
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:
ImmutableArray<T>?ImmutableDictionary<string, T>?We looked at
ImmutableListbut found the performance wasn't right.We considered
FrozenDictionarybut 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.
stephentoub commentedon Jan 14, 2026
I'm not sure what that means?
In general, you can use
IReadOnlyDictionary<>and treat the concrete implementation as an implementation detail. If you don't care about downcasting, you can useDictionary<>. If you do, you can useReadOnlyDictionary<>around aDictionary<>. 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, considerFrozenDictionary<>.ImmutableDictionary<>is almost never what you want.jasoncouture commentedon May 12, 2026
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
Benchmark code
What NOT supporting this does, is either force a micro-optimization
(That is often not an optimization at all), or make things mutable.