繁体   English   中英

使用JSON解析C#字典

[英]Parsing C# Dictionary with JSON

我正在尝试使用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);
        }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM