gpt4 book ai didi

c# - 将字典序列化为json文件

转载 作者:行者123 更新时间:2023-12-05 06:45:09 25 4
gpt4 key购买 nike

我正在尝试将字典序列化为 json,但它对我不起作用。

这是我的字典:

public Dictionary<string, Dictionary<string, string>> roaming = new Dictionary<string,Dictionary<string, string>>();

这就是我尝试序列化它的方式:

string json = JsonConvert.SerializeObject(this.client); // the dictionary is inside client object
//write string to file
System.IO.File.WriteAllText(@"path", json);

我做错了吗? (对于类型为 int 或 string 的成员,它工作得很好)。

最佳答案

对我来说工作正常,可能是库版本或其中包含的数据有问题。这是我能够开始工作的:

简单的“客户端”类(根据你的嵌套字典集做一些简单的翻译):

public class Client
{
public Dictionary<string, Dictionary<string, string>> roaming
{
get { return this._roaming ?? (this._roaming = new Dictionary<string, Dictionary<string, string>>()); }
set { this._roaming = value; }
}
private Dictionary<string, Dictionary<string, string>> _roaming;


public Client()
{
this.roaming.Add("en", new Dictionary<string, string> {
{ "login", "login" },
{ "logout", "logout" },
{ "submit", "submit" }
});
this.roaming.Add("sp", new Dictionary<string, string> {
{ "login", "entrar" },
{ "logout", "salir" },
{ "submit", "presentar" }
});
}
}

然后,实例化和序列化:

Client client = new Client();
String json = JsonConvert.SerializeObject(client, Newtonsoft.Json.Formatting.Indented);

以及[预期的]结果:

{
"roaming": {
"en": {
"login": "login",
"logout": "logout",
"submit": "submit"
},
"sp": {
"login": "entrar",
"logout": "salir",
"submit": "presentar"
}
}
}

关于c# - 将字典序列化为json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25405184/

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