简体   繁体   English

JObject JSON 内部属性排序

[英]JObject JSON Inner Property sort

I have 3 levels of JSON object and trying to sort based on one of the inner-element.我有 3 个级别的 JSON object 并尝试根据内部元素之一进行排序。

Here is the sample JSON.这是示例 JSON。

public class Program
{
    public static void Main()
    {
        string myJSON = @"
            {
              ""items"": ""2"",
              ""documents"": [
                {
                  ""document"": {
                    ""libraryId"": ""LIB0001"",
                    ""id"": ""100"",
                    ""elements"": {
                      ""heading"": {
                        ""elementType"": ""text"",
                        ""value"": ""My Heading 1""
                      },     
                      ""date"": {
                        ""elementType"": ""datetime"",
                        ""value"": ""2020-07-03T20:30:00-04:00""
                      }
                    },
                    ""name"": ""My Name 1 "",
                    ""typeId"": ""10ed9f3f-ab41-45a9-ba24-d988974affa7""
                  }
                },
                {
                  ""document"": {
                    ""libraryId"": ""LIB0001"",
                    ""id"": ""101"",
                    ""elements"": {
                      ""heading"": {
                        ""elementType"": ""text"",
                        ""value"": ""My Heading 2""
                      },       
                      ""date"": {
                        ""elementType"": ""datetime"",
                        ""value"": ""2020-07-03T20:30:00-04:00""
                      }         
                    },
                    ""name"": ""My Name 2"",
                    ""typeId"": ""10ed9f3f-ab41-45a9-ba24-d988974affa7""
                  }
                }
              ]
            }";
        
        JObject resultObject = JObject.Parse(myJSON);
        
    
        var sortedObj = new JObject(
            resultObject.Properties().OrderByDescending(p => p.Value)
        );

        string output = sortedObj.ToString();
        Console.WriteLine(output);
        
    
    }
}

I would like to sort based the "date" field.我想根据“日期”字段进行排序。 Appreciate any help.感谢任何帮助。

You can replace documents json array with sorted one using json path to sort it:您可以使用 json 路径将documents json 数组替换为排序的数组:

resultObject["documents"] = new JArray(resultObject["documents"]
        .Children()
        .OrderBy(p => p.SelectToken("$.document.elements.date.value").Value<DateTime>()));
Console.WriteLine(resultObject.ToString());

Or using indexer access:或使用索引器访问:

resultObject["documents"] = new JArray( resultObject["documents"]
        .Children()
        .OrderBy(p => p["document"]["elements"]["date"]["value"].Value<DateTime>()));

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

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