开发者

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 s开发者_StackOverflow社区ituation?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜