Is it possible to use a JSON.NET dictionary if the key is a non-string object?

I would like to have a GET controller action that returns a JSON serialization dictionary. The key to the dictionary is a simple class with two primitives as properties - let's call it ClassOne. However, when I try to use JSON in the dictionary, I get the following error:

System.Collections.Generic.Dictionary`2[[ClassOne],[ClassTwo]]' is not supported for serialization/deserialization of a dictionary, keys must be strings or objects. 

The phrase "keys must be strings or objects" implies that it is possible to serialize a dictionary that contains objects as its keys. However, I cannot find a way to do this. What are my options in this situation?

+6
source share
1 answer

Oh no. A dictionary from .net will be serialized to a hash in Javascript. A hash can only contain strings as keys, so you cannot serialize a non-linear key. You can simply convert the dictionary to serializable, like this:

 myDictionary.ToDictionary(k => k.Key.Prop1 + "|" + k.Key.Prop2, v => v.Value); 

Perhaps it would be cleaner to override ClassOne a ToString and simply call k.Key.ToString() in the code above.

+7
source

Source: https://habr.com/ru/post/892184/


All Articles