I would like to have controller GET action that returns a JSON-serialized dictionary. The key to the dictionary is a simple class with two primitives as properties - call it ClassOne. However, I receive the following error when attempting to JSON the dictionary:
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 has objects as its keys. However, I cannot find a way to do so. What are my options in this situation?
Well, no. A dictionary from .net would serialize to a hash in Javascript. A hash can only have strings as keys, so you wouldn't be able to serialize a non-string key. You can simply transform your dictionary into a serializable one like this:
myDictionary.ToDictionary(k => k.Key.Prop1 + "|" + k.Key.Prop2, v => v.Value);
Perhaps cleaner would be to give ClassOne
a ToString
override and just call k.Key.ToString()
in the code above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With