2014-09-01 24 views
0

我有麻烦在正确的格式发送JSON数据到这个C#方法:传递JSON的C#方法用词典<INT,列表<int>>作为参数

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

你在使用什么串行器?如果您使用的是默认的.net序列化,我建议您使用处理字典序列化的JSON序列化程序,并且比默认的序列化程序更高效。 – 2014-09-01 07:42:06

+0

因为您使用ajax发送json对象,请尝试以下链接:http://www.codeproject.com/Articles/773102/Redirect-and-Post-JSON-Object-in-ASP-NET-MVC您可能只需更换带有NewtonSoft JSON序列化程序的默认JavasScriptSerializer。 – 2014-09-01 07:45:29

回答

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); 

当改变它字典<串,列表< INT>>它的工作原理:

JSON:{ “0”:[1,2]中, “1” :[3,4]}

如果需要,你当然可以解析这些字符串来输入。

希望它能帮助:)

+0

谢谢。需要改变:'var bar = {“0”:[1,2],“1”:[3,4]};'和'public bool SubmitEducationReply(int educationId,Dictionary > questionandanswers)''。 – 2014-09-01 13:46:27

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]} 

所以你不应该有任何问题了。

相关问题