解析Json字符串并基于c#中的属性进行排序

本文关键字:属性 排序 字符 Json 字符串 串并 解析 | 更新日期: 2023-09-27 18:04:12

我正在制作一个窗口应用程序,其中有一个json字符串,如

{
"0":{"UID":"3182713a-60de-4576-ad82-6804d2acf2b7","Rating":-1},
"1":{"UID":"eb41478e-e9bc-428e-8203-482f6a329666","Rating":-13},
"2":{"UID":"a0922817-e706-4478-8995-d258bada488d","Rating":6.0033992049},
"3":{"UID":"e0716752-56f4-49af-a811-ae55c69baa3d","Rating":-4.9836395671},
"4":{"UID":"ec6bf376-17b5-4a9e-92be-990557551cd0","Rating":-7.754526396}
}

我想通过评级对其进行解析和排序。

解析Json字符串并基于c#中的属性进行排序

您需要将JSON反序列化为Dictionary<int, YourClass>

的例子:

var json = @"{
""0"":{""UID"":""3182713a-60de-4576-ad82-6804d2acf2b7"",""Rating"":-1},
""1"":{""UID"":""eb41478e-e9bc-428e-8203-482f6a329666"",""Rating"":-13},
""2"":{""UID"":""a0922817-e706-4478-8995-d258bada488d"",""Rating"":6.0033992049},
""3"":{""UID"":""e0716752-56f4-49af-a811-ae55c69baa3d"",""Rating"":-4.9836395671},
""4"":{""UID"":""ec6bf376-17b5-4a9e-92be-990557551cd0"",""Rating"":-7.754526396}
}";

var result = JsonConvert.DeserializeObject<Dictionary<int,MyCustomClass>>(json);

MyCustomClass

public class MyCustomClass
{
    public Guid UID {get;set;}
    public decimal Rating {get;set;}
}

Dictionary<int, MyCustomClass>中,int是Json中的数字键。

注意:我在这里使用Newtonsoft Json。

完成上述操作后,可以使用LINQ对其进行如下排序:

var sorted = result.OrderBy(x => x.Value.Rating);
// OR
var sorted = result.OrderByDescending(x => x.Value.Rating);