澄清我的问题,我想使用JToken.SelectTokens Method (String)
中的Namespace: Newtonsoft.Json.Linq
。如何使用方法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",
}
}
}
EDITED
这是原始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();
}
}
}
答案 0 :(得分:1)
试试这个:
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"
}
}
}
]
}
答案 1 :(得分:1)
您可以尝试以下两种方法之一:
foreach (var test in unit_ids)
{
var approach1 = test.Children().Children().Count();
var approach2 = test.First.SelectTokens("*").Count();
}