我有一些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);
答案 0 :(得分:3)
尽管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)");