admin管理员组文章数量:1405632
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);
}
});
}
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);
}
});
}
Share
Improve this question
asked Sep 3, 2011 at 13:02
user470760user470760
1
- It seems that you're adding the same key, with different values in your C# Dictionary. Change the key names. – user278064 Commented Sep 3, 2011 at 13:11
1 Answer
Reset to default 6A 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);
});
});
本文标签: javascriptParsing C Dictionary with JSONStack Overflow
版权声明:本文标题:javascript - Parsing C# Dictionary with JSON - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744895705a2631050.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论