解析C#字典使用JSON [英] Parsing C# Dictionary with JSON

查看:294
本文介绍了解析C#字典使用JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的JSON C#应用程序检索的键/值对的字典,但我什么地方搞砸了。这是我第一次使用JSON,所以我可能只是在做一些愚蠢的事。



C#代码:

 否则如果(string.Equals(请求,getchat))
{
串时间戳= DateTime.Now.ToString(YYYY.MM.DD HH:MM: SS);

&字典LT;字符串,字符串>数据=新词典与LT;字符串,字符串>();
data.Add(时间戳,随机信息);
data.Add(时间戳,第二届聊天味精);
data.Add(时间戳,控制台行了!);

返回Response.AsJson(数据);
}



使用Javascript:

 函数getChatData()
{
$ .getJSON(数据源+?REQ = getchat,,功能(数据)
{
$。每次(数据,功能(键,VAL)
{
addChatEntry(KEY,VAL);
}
});
}


解决方案

一个字典没有在字典序列化为阵列。此外键必须是独一无二的,你可能会得到一个异常具有相同名称的密钥已经被插入,当您尝试运行服务器端代码中使用值的数组尝试:

  VAR数据=新的[] 
{
新的{键=时间戳值=随机消息},
新的{键=时间戳值=第二届聊天味精},
新的{键=时间戳值=}
}控制台行!;
返回Response.AsJson(数据);

序列化的JSON应该是这个样子:

  [
{关键:2011年9月3日15时11分10秒,值:随机消息},
{关键:2011.09 0.03 15时11分10秒,值:第二届聊天味精},
{关键:2011年9月3日15时11分10秒,值:控制台线路}
]

现在在你的JavaScript可以循环:

  $的getJSON(数据源,{REQ:getchat'},功能(数据){
$。每次(数据,功能(索引,项目){
//使用item.key和item.value访问各自的属性
addChatEntry(item.key,item.value);
});
});


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

这篇关于解析C#字典使用JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆