System.Text.Json: The collection type ‘System.Collections.Generic.Dictionary[System.Int32,System.String]is not supported
Issue Description
JSON serialization using System.Text.Json produces the below error in the.NET/.NET Core application.
System.NotSupportedException: 'The collection type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]' is not supported.'
Resolution
This issue is more because the new .NET /ASP.NET Core 3.1 or .NET 5.0 framework has removed the dependency on JSON.NET(Newtonsoft) and uses its own JSON serializer i.e. ‘System.Text.Json‘.
System.Text.Json has built-in support for only Dictionary types that match Dictionary< string, TValue>.
It produces NotSupportedException for the non-string Keys like Int32 or Enum in the serialization.
As per specification and design, there are known limitations in the System.Text.Json serializer for the serialization.
Resolution 1 (Recommended):
These limitations can be overcome by using Custom DictionaryConverter.
I have the dictionary object below,
Dictionary<int, string> dictEmployess = new Dictionary<int, string>();
The issue can be fixed by using DictionaryInt32Converter as a converter in the serialization option.
var serializeOptions = new JsonSerializerOptions();
serializeOptions.Converters.Add(new DictionaryInt32Converter());
jsonoutPut = JsonSerializer.Serialize(dictEmployess);
Please see here an example of DictionaryInt32Converter.
Resolution 2:
Continue using Newtonsoft(JSON.NET) as is. This option is very easy however you end up using a big fat Newtonsoft library.
jsonoutPut = JsonConvert.SerializeObject(dictEmployess);
Did I miss anything else in these resolution steps?
Did the above steps resolve your issue? Please sound off your comments below!
Happy Coding !!
Reference :
- DictionaryInt32Converter example.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.
Nice solutions.
I just used the second option and it worked fine with a complex Dictionary type.
Thank you
Hi Kprive – Thanks. Glad it helped you!
Thank you.