我正在嘗試將 Dictionary 序列化為 .json 文件并從當前文件中反序列化它。我有下一個代碼:string filePath = AppDomain.CurrentDomain.BaseDirectory;Dictionary<string, int> dict = new Dictionary<string, int>() { { "aaa", 1}, { "bbb", 2}, { "ccc", 3}};這很好用File.WriteAllText(filePath + "IndexedStrings.json", JsonConvert.SerializeObject(dict, Newtonsoft.Json.Formatting.Indented));結果是:{ "aaa": 1, "bbb": 2, "ccc": 3}但是當我使用這個時:File.WriteAllText(filePath + "IndexedStrings.json", JsonConvert.SerializeObject(dict.OrderByDescending(kvp => kvp.Value), Newtonsoft.Json.Formatting.Indented));結果是:[ { "Key": "ccc", "Value": 3 }, { "Key": "bbb", "Value": 2 }, { "Key": "aaa", "Value": 1 }]我應該使用不同的方式來序列化Dictionary()還是如何反序列化它?
1 回答

烙印99
TA貢獻1829條經驗 獲得超13個贊
正如其他人所指出的,通常您不應該關心對象屬性的順序。這是對象和數組之間的根本區別之一。
但是,如果您堅持,您可以JObject從預先訂購的對中手動構造 a 然后將其序列化:
var jObj = new JObject();
foreach (var kv in dict.OrderByDescending(x => x.Value))
{
jObj.Add(kv.Key, kv.Value);
}
var result = JsonConvert.SerializeObject(jObj, Newtonsoft.Json.Formatting.Indented);
- 1 回答
- 0 關注
- 132 瀏覽
添加回答
舉報
0/150
提交
取消