2014-09-01 22 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]} 

所以你不應該有任何問題了。

相關問題