使用LINQ查询JSONLINQ、JSON

2023-09-03 06:48:47 作者:素颜马尾帆布鞋

我有一个JSON响应,我从一个API调用接收。它有几个嵌套层次,如下图所示(这是一个片段):

I have a Json response that I receive from an API call. It has several nested levels as show below (this is a snippet):

"Items": [
  {
    "Result": {
      "Id": "191e24b8-887d-e111-96ec-000c29128cee",
      "Name": "Name",
      "StartDate": "2012-04-03T00:00:00+01:00",
      "EndDate": null,
      "Status": {
        "Name": "Active",
        "Value": 5
      },
      "Client": {
        "Id": "35ea10da-b8d5-4ef8-bf23-c829ae90fe60",
        "Name": "client Name",
        "AdditionalItems": {}
      },
      "ServiceAgreement": {
        "Id": "65216699-a409-44b0-8294-0e995eb05d9d",
        "Name": "Name",
        "AdditionalItems": {
          "ScheduleBased": true,
          "PayFrequency": {
            "Id": "981acb72-8291-de11-98fa-005056c00008",
            "Name": "Weekly",
            "AdditionalItems": {}
          },
          "PayCycle": [
            {
              "Name": "Schedule Based",
              "ScheduleBased": true,
              "SelfBilling": false,
              "Id": "a8a2ecc4-ff79-46da-a135-743b57808ec3",
              "CreatedOn": "2011-09-16T23:32:19+01:00",
              "CreatedBy": "System Administrator",
              "ModifiedOn": "2011-09-16T23:32:19+01:00",
              "ModifiedBy": "System Administrator",
              "Archived": false
            }
          ]
        }
      },
}
]
...

我想要做的是使用LINQ的PayCycle节点retreive数据。我可以举例来说得到与真正使用Result.ServiceAgreement.AdditionalItems.SchedultedBased使用下面的LINQ在控制器的值项:

What I want to do is retreive the data from the PayCycle node using Linq. I can for example get the items with a value of true using Result.ServiceAgreement.AdditionalItems.SchedultedBased using the following Linq in the Controller:

var result = from p in data["Data"]["Items"].Children()
             where (bool)p["Result"]["ServiceAgreement"]["AdditionalItems"]["ScheduleBased"] == true
             select new
             {
                 Name = (string)p["Result"]["Client"]["Name"],
                 Id = (string)p["Result"]["Client"]["Id"]
             };

现在我需要获得 Result.ServiceAgreement.AdditionalItems.Paycycle.ScheduleBased SelfBilling 属性。如何做到这一点,如果PayCycle也是一个数组,如何让孩子们为我在LINQ的Data.Items做上面,这样我可以有这两个项目的where子句过滤器?

Now I need to get Result.ServiceAgreement.AdditionalItems.Paycycle.ScheduleBased and SelfBilling properties. How do I do this if PayCycle is also an array, how do I get the children as I did with Data.Items in the Linq above so that I can have the where clause filter on both these items?

推荐答案

可以反序列化JSON成动态对象,然后使用LINQ对象:

You can deserialize the JSON into a dynamic object, and then use Linq to Objects:

    [TestMethod]
    public void TestMethod1()
    {
        const string json = @"""Items"": [
{
""Result"": {
  ""Id"": ""191e24b8-887d-e111-96ec-000c29128cee"",
  ""Name"": ""Name"",
  ""StartDate"": ""2012-04-03T00:00:00+01:00"",
  ""EndDate"": null,
  ""Status"": {
    ""Name"": ""Active"",
    ""Value"": 5
  },
  ""Client"": {
    ""Id"": ""35ea10da-b8d5-4ef8-bf23-c829ae90fe60"",
    ""Name"": ""client Name"",
    ""AdditionalItems"": {}
  },
  ""ServiceAgreement"": {
    ""Id"": ""65216699-a409-44b0-8294-0e995eb05d9d"",
    ""Name"": ""Name"",
    ""AdditionalItems"": {
      ""ScheduleBased"": true,
      ""PayFrequency"": {
        ""Id"": ""981acb72-8291-de11-98fa-005056c00008"",
        ""Name"": ""Weekly"",
        ""AdditionalItems"": {}
      },
      ""PayCycle"": [
        {
          ""Name"": ""Schedule Based"",
          ""ScheduleBased"": true,
          ""SelfBilling"": false,
          ""Id"": ""a8a2ecc4-ff79-46da-a135-743b57808ec3"",
          ""CreatedOn"": ""2011-09-16T23:32:19+01:00"",
          ""CreatedBy"": ""System Administrator"",
          ""ModifiedOn"": ""2011-09-16T23:32:19+01:00"",
          ""ModifiedBy"": ""System Administrator"",
          ""Archived"": false
        }
      ]
    }
  }
}
}
]";
        dynamic data = System.Web.Helpers.Json.Decode("{" + json + "}");

        var result = from i in (IEnumerable<dynamic>)data.Items
                     where i.Result.ServiceAgreement.AdditionalItems.ScheduleBased == true
                     select new
                            {
                                i.Result.Client.Name,
                                i.Result.Client.Id
                            };

        Assert.AreEqual(1, result.Count());
        Assert.AreEqual("client Name", result.First().Name);
        Assert.AreEqual("35ea10da-b8d5-4ef8-bf23-c829ae90fe60", result.First().Id);
    }

请注意,我不得不加括号{和}在你的例子JSON字符串,否则.NET JSON解析器不喜欢它。

Note that I had to add brackets { and } around your example json string, or else the .NET json parser doesn't like it.