简体   繁体   中英

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. This is my first time with JSON so I am probably just doing something stupid.

C# Code:

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

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:

[ 
    { "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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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