我无法以正确的格式将JSON数据发送到此C#方法:
public bool MyMethod(int foo, Dictionary<int, List<int>> bar)
我不知道的是格式化bar
变量:
var bar = {};
bar['1'] = [1, [1, 2]];
bar['2'] = [1, [1, 2, 3]];
bar['3'] = [1, [1, 2]];
$.ajax({
...
data: '{"foo":1, "bar":' + JSON.stringify(bar) + '}'
});
.NET给我一个'InvalidOperationException`,其中包含以下消息:
Type 'System.Collections.Generic.Dictionary is not supported for
serialization/deserialization of a dictionary, keys must be strings or objects.
答案 0 :(得分:1)
我为此尝试了快速逆向工程并得到了这个:
Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089],[System.Collections.Generic.List`1 [[System.Int32,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]字典的序列化/反序列化不支持],mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]',键必须是字符串或对象。
代码:
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>{
{0, new List<int>{1,2}},
{1, new List<int>{3,4}}
};
var serializer = new JavaScriptSerializer();
ViewBag.Message = serializer.Serialize(dict);
将其更改为Dictionary&lt; string,List&lt; INT&GT; &GT;它有效:
Json:{“0”:[1,2],“1”:[3,4]}
如果需要,您当然可以稍后将这些字符串解析为整数。
希望有所帮助:)
答案 1 :(得分:1)
使用NewtonSoft json转换器:
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>{
{0, new List<int>{1,2}},
{1, new List<int>{3,4}}
};
var json = JsonConvert.SerializeObject(dict);
// json = {"0":[1,2],"1":[3,4]}
所以你不应该有任何问题。