c# - 对象字典不适用于 JSON

标签 c# javascript json object dictionary

我花了太多时间试图找出如何使用 JS 和 JSON 从我的 C# 应用程序中提取我需要的所有值。当我只使用简单的结构(例如数组)时它工作正常,但我需要能够在运行时增加列表。

现在,我能想到的最好办法是用一个递增的键值和其他 3 个值作为类对象来创建字典。但是,这似乎使我的 C# 应用程序崩溃了。

执行此操作的最佳方法是什么?

相关C#代码:

public class ChatData
{
    string userName;
    string message;
    System.DateTime timestamp;

    public ChatData(string name, string msg)
    {
        userName = name;
        message = msg;
        timestamp = System.DateTime.Now;
    }
}

        else if (string.Equals(request, "getchat"))
        {
            //string since = Request.Query.since;

            Dictionary<int, ChatData> data = new Dictionary<int, ChatData>();

            data.Add(1, new ChatData("bob", "hey guys"));
            data.Add(2, new ChatData("david", "hey you"));
            data.Add(3, new ChatData("jill", "wait what"));

            return Response.AsJson(data);
        }

相关 Javascript:

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

最佳答案

你还没有解释什么是 Response.AsJson 以及它是如何实现的,但是如果它使用 JavaScriptSerializer 你会得到以下异常:

Unhandled Exception: System.ArgumentException: Type 'System.Collections.Generic. Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[ChatData, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' is not supported for serialization/deserialization of a dictionary, keys must be strings or objects.

这是不言自明的。如果您打算对此结构进行 JSON 序列化,则不能使用整数作为键。此外,因为您的 ChatData 类不再具有默认/无参数构造函数,您将无法将 JSON 字符串反序列化回此类(但我想您还不需要这个)。

因此,您的问题的一种可能解决方案是使用:

Dictionary<string, ChatData> data = new Dictionary<string, ChatData>();
data.Add("1", new ChatData("bob", "hey guys"));
data.Add("2", new ChatData("david", "hey you"));
data.Add("3", new ChatData("jill", "wait what"));

现在当然是这么说的,看看你注释掉的 javascript 和你打算做什么,正如我已经在你的 previous question 中解释过的那样, 字典没有序列化为 javascript 数组,所以你不能遍历它们。

长话短说,定义一个类:

public class ChatData
{
    public string Username { get; set; }
    public string Message { get; set; }
    public DateTime TimeStamp { get; set; }
}

然后填充一个这个类的数组:

var data = new[]
{
    new ChatData { Username = "bob", Message = "hey guys" },
    new ChatData { Username = "david", Message = "hey you" },
    new ChatData { Username = "jill", Message = "wait what" },
};
return Response.AsJson(data);

最后消费:

$.getJSON(dataSource, { req: 'getchat' }, function (data) {
    $.each(data, function(index, element) {
        // do something with element.Username and element.Message here, like
        $('body').append(
            $('<div/>', {
                html: 'user: ' + element.Username + ', message:' + element.Message
            })
        );
    });
});

关于c# - 对象字典不适用于 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7299423/

相关文章:

php - 如何将数据从 KnockOut 发送到 MySql 的 Php?

c# - if语句和 "?/:"运算符的区别

javascript - 为什么我的计算器会连接而不是执行运算?

javascript - 如何将两个或多个 JSON 对象求和为一个

javascript - 如何使用弹出框输入更改CSS(背景颜色)

python - 在 Flask-sqlalchemy 和 Postgresql 中使用 JSON 类型

javascript - JSON.stringify反转?

c# - 针对 csc.exe 中的特定框架版本

c# - 如何从计时器触发器获取 azure 函数运行位置的主机名?

c# - 字符串未定义