解析Json字符串并根据C#中的属性进行排序

时间:2016-08-26 10:49:30

标签: c# json winforms

我正在开发一个窗口应用程序,其中有一个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}
}

我想通过评分来解析和排序。请建议我如何实现它。

1 个答案:

答案 0 :(得分:3)

您需要将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);