用JSON解析C#字典

我正在尝试使用JSON从我的C#应用​​程序中检索键/值对的字典,但我在某个地方搞砸了。 这是我第一次使用JSON,所以我可能只是在做一些愚蠢的事情。

C#代码:

else if (string.Equals(request, "getchat")) { string timestamp = DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss"); Dictionary data = new Dictionary(); data.Add(timestamp, "random message"); data.Add(timestamp, "2nd chat msg"); data.Add(timestamp, "console line!"); return Response.AsJson(data); } 

使用Javascript:

 function getChatData() { $.getJSON(dataSource + "?req=getchat", "", function (data) { $.each(data, function(key, val) { addChatEntry(key, val); } }); } 

字典未序列化为数组。 字典中的键也必须是唯一的,当您尝试运行服务器端代码时,可能会遇到一个例外,即已经插入了具有相同名称的键。 尝试使用一组值:

 var data = new[] { new { key = timestamp, value = "random message" }, new { key = timestamp, value = "2nd chat msg" }, new { key = timestamp, value = "console line!" }, }; return Response.AsJson(data); 

序列化的json看起来像这样:

 [ { "key":"2011.09.03 15:11:10", "value":"random message" }, { "key":"2011.09.03 15:11:10", "value":"2nd chat msg" }, { "key":"2011.09.03 15:11:10", "value":"console line!" } ] 

现在在你的javascript中你可以循环:

 $.getJSON(dataSource, { req: 'getchat' }, function (data) { $.each(data, function(index, item) { // use item.key and item.value to access the respective properties addChatEntry(item.key, item.value); }); });