简体   繁体   English

使用JSON解析C#字典

[英]Parsing C# Dictionary with JSON

I am trying to retrieve a Dictionary of key/value pairs from my C# application with JSON, but I am screwing up somewhere. 我正在尝试使用JSON从我的C#应用​​程序中检索键/值对的字典,但是我在某个地方搞砸了。 This is my first time with JSON so I am probably just doing something stupid. 这是我第一次使用JSON,因此我可能只是在做一些愚蠢的事情。

C# Code: 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: Javascript:

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

A dictionary is not serialized as array. 字典未序列化为数组。 Also keys in a dictionary must be unique and you will probably get an exception that a key with the same name has already be inserted when you try to run your server side code. 另外,词典中的键必须唯一,并且当您尝试运行服务器端代码时,您可能会得到一个例外,即已经插入了具有相同名称的键。 Try using an array of values: 尝试使用值数组:

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

The serialized json should look something like this: 序列化的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!" }
]

now in your javascript you can loop: 现在在您的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