如何对 JObject 数组进行排序



在我的代码中,我需要根据日期对JObject数组进行排序。 怎么做? 我的数据如下所示 我需要按降序排序。

"His": [
        {
        "Date": "6/17/2019 6:00:00 PM",
        "StatusMsg": ""
    },
    {
        "Date": "6/17/2019 11:08:48 AM",
        "StatusMsg": ""
    },
    {
        "Date": "6/17/2019 7:38:00 AM",
        "StatusMsg": ""
    },
    {
        "Date": "6/17/2019 5:00:00 AM",
        "StatusMsg": ""
    },
    {
        "Date": "6/16/2019 6:16:00 PM",
        "StatusMsg": ""
    },
    {
        "Date": "6/15/2019 9:20:00 PM",
        "StatusMsg": ""
    },
    {
        "Date": "6/13/2019 2:00:00 PM",
        "StatusMsg": ""
    },
    {
        "Date": "6/13/2019 1:37:00 PM",
        "StatusMsg": ""
    },
    {
        "Date": "6/13/2019 2:39:00 AM",
        "StatusMsg": ""
    },
    {
        "Date": "6/13/2019 2:11:00 AM",
        "StatusMsg": ""
    },
    {
        "Date": "6/13/2019 2:08:00 AM",
        "StatusMsg": ""
    },
    {
        "Date": "6/12/2019 3:50:00 PM",
        "StatusMsg": ""
    }
    ]

我将结果分配给JObject.这是我的示例输入。任何人都试图帮助我。谢谢。

就像马克在问题评论中所说的那样 - 为什么不使用常规类:

public class Rootobject
{
    public His[] His { get; set; }
}
public class His
{
    public string Date { get; set; }
    public string StatusMsg { get; set; }
    public string Msg { get; set; }
    public string StatusDate { get; set; }
}

反序列化它并利用 LINQ:

var json = "{rnt"His": [rn        {rn            "Date": "3/18/2019 6:30:45 PM",rn            "StatusMsg": "test3"rn        },rn        {rn            "Date": "3/21/2019 12:13:02 PM",rn            "Msg": "test2"rn        },rn        {rn            "StatusDate": "3/17/2019 9:26:00 AM",rn            "Msg": "test1"rn        },rn    ]rn}";
var obj = JsonConvert.DeserializeObject<Rootobject>(json);
var sortedList = obj.His.OrderByDescending(o => o.Date).ToList();

编辑:如果你不想使用一个类,那么你可以做这样的事情:

var json = "{rnt"His": [{rnttt"Date": "3/18/2019 6:30:45 PM",rnttt"StatusMsg": "test3"rntt}, {rnttt"Date": "3/21/2019 12:13:02 PM",rnttt"Msg": "test2"rntt}, {rnttt"Date": "3/17/2019 9:26:00 AM",rnttt"Msg": "test1"rntt},rnt]rn}rn";
JObject jobj = JObject.Parse(json);
JArray array = jobj["His"];
JArray sorted = new JArray(array.OrderByDescending(obj => (DateTime)obj["Date"]));

这假设每个 JSON 对象将始终具有一个名为"Date"的属性

相关内容

  • 没有找到相关文章

最新更新