gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:58:17 24 4
gpt4 key购买 nike

我花了太多时间试图找出如何使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com