简体   繁体   English

如何按值对JObject进行排序

[英]How to sort a JObject by value

I have some JSON: 我有一些JSON:

{
    "AI": "1",
    "AJ": "0",
    "AM": "0",
    "AN": "0",
    "BK": "5",
    "BL": "8",
    "BM": "0",
    "BN": "0",
    "BO": "4",
    "CJ": "0",
    "CK": "2"
}

I'd like to sort it by number, highest to lowest, and get the property with the highest number by just writing the first index of the JSON. 我想按数字排序,从最高到最低,并通过编写JSON的第一个索引获得具有最高编号的属性。 Can you help me? 你能帮助我吗?

This is what I have so far: 这是我到目前为止:

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);

Although the JSON spec defines a JSON object as an unordered set of properties, Json.Net's JObject class does appear to maintain the order of properties within it. 尽管JSON规范将JSON对象定义为无序的属性集,但Json.Net的JObject类似乎确实维护了其中的属性顺序。 You can sort the properties by value like this: 您可以按值对属性进行排序,如下所示:

JObject voteObj = JObject.Parse(voteJson);

var sortedObj = new JObject(
    voteObj.Properties().OrderByDescending(p => (int)p.Value)
);

string output = sortedObj.ToString();

You can then get the property with the highest value like this: 然后,您可以获得具有最高值的属性,如下所示:

JProperty firstProp = sortedObj.Properties().First();
Console.WriteLine("Winner: " + firstProp.Name + " (" + firstProp.Value + " votes)");

Working demo: https://dotnetfiddle.net/dptrZQ 工作演示: https//dotnetfiddle.net/dptrZQ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM