c# json计算node's子节点

本文关键字:子节点 json 计算 node | 更新日期: 2023-09-27 18:03:29

澄清我的问题,我想从Namespace: Newtonsoft.Json.Linq中使用JToken.SelectTokens Method (String)。如何使用方法SelectTokens("")获得每个节点"174637" (unit_id)和"174638" (unit_id)的子节点数?对于第一个节点,我应该得到1和第二个2。我试过了:

foreach (var test in unit_ids) { //takes every unit_id, one by one
     var children_of_unit_id = test.SelectTokens("*.[*]").count();
}

但是它什么也没给我。

"174637": {
  "1": {
    "value_symbol": "3",
    "exam_session_number": 1,
    "exam_id": 207983,
    "value_description": {
      "en": "satisfactory",
    }
  }
}
"174638": {
  "1": {
    "value_symbol": "3",
    "exam_session_number": 1,
    "exam_id": 207984,
    "value_description": {
      "en": "satisfactory",
    }
  }
  "2": {
    "value_symbol": "3",
    "exam_session_number": 2,
    "exam_id": 207985,
    "value_description": {
      "en": "satisfactory",
    }
  }  
}

Json:

{
  "grades": {
    "course_units_grades": {
      "173565": {
        "1": {
          "value_symbol": "3,5",
          "exam_session_number": 1,
          "exam_id": 208798,
          "value_description": {
            "en": "satisfactory plus",
            "pl": "dst+"
          }
        }
      },
      "173566": {
        "1": {
          "value_symbol": "2",
          "exam_session_number": 1,
          "exam_id": 208797,
          "value_description": {
            "en": "unsatisfactory",
          }
        },
        "2": {
          "value_symbol": "3",
          "exam_session_number": 2,
          "exam_id": 208797,
          "value_description": {
            "en": "satisfactory",
          }
        }
      }
    },
    "course_grades": {}
  }
}

所以它看起来像这样:

foreach (var t in json_grade)//take every "grades" element, one by one
{
    var test = t.SelectTokens("['grades'].['course_units_grades']");
    foreach (var unit_ids in test)
    {
        foreach (var test in unit_ids) { //takes every unit_id, one by one
             var children_of_unit_id = test.SelectTokens("*.[*]").count();
        }
    }
}

c# json计算node's子节点

您可以尝试以下两种方法之一:

foreach (var test in unit_ids) 
{
     var approach1 = test.Children().Children().Count();
     var approach2 = test.First.SelectTokens("*").Count();
}

Dotnetfiddle Demo

试试这个:

 var token = JToken.Parse(j)["unit_id"][0].ToList().Count;

示例JSON:

{
  "174637": [
    {
      "1": {
        "value_symbol": "3",
        "exam_session_number": "1",
        "exam_id": "207983",
        "value_description": {
          "en": "value_description"
        }
      }
    }
  ],
  "174638": [
    {
      "1": {
        "value_symbol": "3",
        "exam_session_number": "1",
        "exam_id": "207983",
        "value_description": {
          "en": "value_description"
        }
      },
      "2": {
        "value_symbol": "3",
        "exam_session_number": "1",
        "exam_id": "207983",
        "value_description": {
          "en": "value_description"
        }
      }
    }
  ]
}