我有一些JSON:
{
"AI": "1",
"AJ": "0",
"AM": "0",
"AN": "0",
"BK": "5",
"BL": "8",
"BM": "0",
"BN": "0",
"BO": "4",
"CJ": "0",
"CK": "2"
}
我想按编号(从高到低)对其进行排序,并通过仅写入JSON的第一个索引来获得具有最高编号的属性.你能帮助我吗?
这是我到目前为止的内容:
string voteJson = File.ReadAllText("vote.json");
Object voteObj = JObject.Parse(voteJson);
//How to sort the object here?
//Saving it
string output = Newtonsoft.Json.JsonConvert.SerializeObject(voteObj,
Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("vote-sorted.json", output);
解决方法:
尽管JSON spec将JSON对象定义为一组无序的属性,但Json.Net的JObject
类似乎确实在其中维护了属性的顺序.您可以像这样按值对属性进行排序:
JObject voteObj = JObject.Parse(voteJson);
var sortedObj = new JObject(
voteObj.Properties().OrderByDescending(p => (int)p.Value)
);
string output = sortedObj.ToString();
然后,您可以像这样获得具有最高值的属性:
JProperty firstProp = sortedObj.Properties().First();
Console.WriteLine("Winner: " + firstProp.Name + " (" + firstProp.Value + " votes)");
工作演示:https://dotnetfiddle.net/dptrZQ