用JSON解析C#字典

1 javascript c# json dictionary

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

C#代码:

        else if (string.Equals(request, "getchat"))
        {
            string timestamp = DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss");

            Dictionary<string, string> data = new Dictionary<string, string>();
            data.Add(timestamp, "random message");
            data.Add(timestamp, "2nd chat msg");
            data.Add(timestamp, "console line!");

            return Response.AsJson(data);
        }
Run Code Online (Sandbox Code Playgroud)

使用Javascript:

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

Dar*_*rov 6

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

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);
Run Code Online (Sandbox Code Playgroud)

序列化的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!" }
]
Run Code Online (Sandbox Code Playgroud)

现在在你的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);
    });
});
Run Code Online (Sandbox Code Playgroud)