![](/img/trans.png)
[英]how to retrieve the value of a kvp in c sharp, using the text of the key?
[英]How to serialize/deserialize Dictionary<string, int>().OrderByDescending(kvp => kvp.Value) to Json?
我正在尝试将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()
还是如何反序列化它?
正如其他人指出的那样,通常您不必关心对象属性的顺序。 这是对象和数组之间的根本区别之一。
但是,如果您坚持要求,则可以从预定对中手动构造一个JObject
,然后对其进行序列化:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.