如何按值对 JObject 进行排序

The*_*aik 6 c# sorting json json.net

我有一些 JSON:

{
    "AI": "1",
    "AJ": "0",
    "AM": "0",
    "AN": "0",
    "BK": "5",
    "BL": "8",
    "BM": "0",
    "BN": "0",
    "BO": "4",
    "CJ": "0",
    "CK": "2"
}
Run Code Online (Sandbox Code Playgroud)

我想按数字从高到低排序,并通过编写 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);
Run Code Online (Sandbox Code Playgroud)

Bri*_*ers 8

尽管JSON 规范将 JSON 对象定义为一组无序的属性,但 Json.Net 的JObject类似乎确实维护了其中属性的顺序。您可以按值对属性进行排序,如下所示:

JObject voteObj = JObject.Parse(voteJson);

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

string output = sortedObj.ToString();
Run Code Online (Sandbox Code Playgroud)

然后,您可以获得具有最高值的属性,如下所示:

JProperty firstProp = sortedObj.Properties().First();
Console.WriteLine("Winner: " + firstProp.Name + " (" + firstProp.Value + " votes)");
Run Code Online (Sandbox Code Playgroud)

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