开发者

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

开发者 https://www.devze.com 2023-03-18 22:55 出处:网络
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

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

精彩评论

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