我正在尝试将字典序列化为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类型的成员,它工作正常)。
答案 0 :(得分:1)
对我来说工作正常,可能是库版本或其中包含的数据的问题。这是我能够工作的原因:
简单的“客户”类(只是根据嵌套字典集进行一些简单的翻译):
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"
}
}
}