Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 376
JustOnePixel Avatar asked Jul 06 '11 22:07

JustOnePixel


1 Answers

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.

like image 79
Milimetric Avatar answered Sep 25 '22 13:09

Milimetric