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:
The serialized json should look something like this:
now in your javascript you can loop: