【问题标题】:C# How to get JSON multiple level nested of multiple same name valuesC#如何获取多个同名值的JSON多级嵌套
【发布时间】:2021-04-28 16:13:02
【问题描述】:

我正在尝试从 JSON 响应中提取一些 JSON 数据值。 我得到了一个 JSON 数据数组,并且已经解析到 JArray 以工作并获取未嵌套的 JProperties 的值。 我不知道如何从包含类别、组件和功能的嵌套信息的属性中获取“id”数据。每个项目的“id”数据计数都不相同。

"items": [
{
  "deviceId": "DeviceNumber", <-Can get these values OK
  "name": "DeviceName",
  "label": "DeviceLabel",
  "locationId": "LocationId",
  "components": [
    {
      "id": "main", <-NEED THIS
      "label": "DeviceLabel",
      "capabilities": [
        {
          "id": "ID1", <-NEED THIS
          "version": 1 <-NEED THIS
        },
        {
          "id": "ID2", <-NEED THIS
          "version": 1 <-NEED THIS
        },
        {
          "id": "ID3", <-NEED THIS
          "version": 1 <-NEED THIS
        }
      ],
      "categories": [
        {
          "name": "CategoryName", <-NEED THIS
          "categoryType": "manufacturer"
        }
      ]
    }
  ],
  "dth": {
    "deviceTypeId": "deviceID"
  },
  "type": "typeID"
},
...Next item with same info

这是我必须在组件之前获取“deviceId”和旁边的其他项目的代码。

        JObject parsed = JObject.Parse(deviceListJSONstring);
        JArray array = (JArray)parsed["items"];
        foreach (JObject item in array.Children<JObject>())
        {
            foreach (JProperty property in item.Properties())
            {

                if (property.Name.Equals("deviceId"))
                {
                    Console.WriteLine(property.Value);
                    deviceID = property.Value.ToString();
                }
                else if (property.Name.Equals("components"))
                {
                #What needs to be here?
                }

我们将不胜感激。

【问题讨论】:

  • 将您的 JSON 复制并粘贴到 json2csharp.com,然后反序列化为该模型。

标签: c# json json.net


【解决方案1】:

我可以通过"SelectToken with JSONPath"获取数据

var componentsIDs = item.SelectToken("$.components[*]");
var capabilitiesIds = item.SelectTokens("$...capabilities[*]");
var categoriesIds = item.SelectTokens("$...categories[*]");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多