Newtonsoft.Json don’t support FrozenDictionary
. I know I can write a JsonConverter
starting from scratch, but it is difficult for me, and FrozenDictionary
is very similar to a Dictionary
when serialize/deserialize. Can I tell Newtonsoft.Json to serialize/deserialize it as Dictionary
in some simple way?
Or is there another question on here with a FrozenDictionaryJsonConverter
already written by someone else?
2
Answers
The problem is FrozenDictionary doesn’t have a new() – personally I’d deal with it by having two properties and dealing with it in your class constructor or something. If you want JSON though
The above isn’t generic, you need to set the types on your json converter settings, but it will work.
Personally, if I had that use case – I would do something like this instead (but with better accessors ofc)
If you’re building a ASP.NET API and want a more generic way to do this, you could use a converter like this:
This uses some reflection to invoke a typed generic method to do the deserialization. It could probably be made faster by caching the constructed method.
While this is likely going to be marginally slower than a converter that you have to supply the key/value types to, it has the benefit that you can register this as a converter on your
JsonSerializerSettings
and it will handle any and allFrozenDictionary
types within your models, without explicitly having to register a container for each key/value type pairing.I want to add that this doesn’t implement the
WriteJson
method because that is already supported by JSON.NET (presumably through theIDictionary<TKey, TValue>
interface), so we don’t have to create our own.