小编典典

JSON计数仅返回1而不是2

json

我有这行代码(总是返回1):

int rowsCount = token["rows"].Count();

其中token [“ rows”]是:

    {
  "component": [
    {
      "tag": "CUT",
      "missingValue": "",
      "format": "Cont",
      "varName": "GPA",
      "label": "Grade point average",
      "element": [
        {
          "startValue": "1",
          "endValue": "249",
          "label": "Lower than 2.50"
        },
        {
          "startValue": "250",
          "endValue": "299",
          "label": "2.50 - 2.99"
        },
        {
          "startValue": "300",
          "endValue": "349",
          "label": "3.00 - 3.49"
        },
        {
          "startValue": "350",
          "endValue": "400",
          "label": "3.50 or higher"
        }
      ]
    },
    {
      "tag": "CAT",
      "missingValue": "",
      "format": "Disc",
      "varName": "STEMMAJ",
      "label": "Major field of study with a focus on STEM fields",
      "element": [
        {
          "value": "1",
          "label": "Math/Computer/Sciences/Engineering/Technologies"
        },
        {
          "value": "2",
          "label": "Social/behavioral sciences"
        },
        {
          "value": "4",
          "label": "Non-STEM field"
        },
        {
          "value": "5",
          "label": "Undecided or not in a degree program"
        }
      ]
    }
  ]
}

我想对组件数量进行计数。

这也不起作用:

token["rows"]["component"].Count();

整个JSON在这里:

    {
  "version": "1.0",
  "createdBy": "PowerStats v1.0",
  "test": "ohoh",
  "DSNumber": {
    "value": "82"
  },
  "title": {
    "value": ""
  },
  "footnote": {
    "value": ""
  },
  "flagRSE": {
    "value": "30,50",
    "symbol": "!,!!"
  },
  "weight": {
    "type": "0",
    "varName": "WTA000",
    "label": "weight_var"
  },
  "filters": {
    "filter_1": {
      "component": {
        "varName": "JOBEARN2",
        "filterType": "Range",
        "format": "Cont",
        "label": "Job: Earnings from work while enrolled (including work-study)",
        "element": {
          "startValue": "1",
          "endValue": "",
          "label": "X >= 1"
        }
      }
    },
    "filter_2": {
      "component": {
        "varName": "JOBROLE2",
        "filterType": "Dist",
        "format": "Disc",
        "label": "Job: Primary role as student or employee (including work-study)",
        "element": {
          "value": "1",
          "label": "A student working to meet expenses"
        }
      }
    }
  },
  "columns": {
    "component": {
      "tag": "CAT",
      "missingValue": "4,5,6,7,8,9,10,13,14,15,16,17,18,19,20,21,22,23,-3",
      "format": "Disc",
      "varName": "MAJORS23",
      "label": "Field of study: undergraduate (23 categories)",
      "element": [
        {
          "value": "0",
          "label": "Undecided"
        },
        {
          "value": "1",
          "label": "Computer and information sciences"
        },
        {
          "value": "2",
          "label": "Engineering and engineering technology"
        },
        {
          "value": "3",
          "label": "Biological and physical science, science tech"
        },
        {
          "value": "11",
          "label": "Personal and consumer services"
        },
        {
          "value": "12",
          "label": "Manufacturing,construction,repair & transportation"
        }
      ]
    }
  },
  "rows": {
    "component": [
      {
        "tag": "CUT",
        "missingValue": "",
        "format": "Cont",
        "varName": "GPA",
        "label": "Grade point average",
        "element": [
          {
            "startValue": "1",
            "endValue": "249",
            "label": "Lower than 2.50"
          },
          {
            "startValue": "250",
            "endValue": "299",
            "label": "2.50 - 2.99"
          },
          {
            "startValue": "300",
            "endValue": "349",
            "label": "3.00 - 3.49"
          },
          {
            "startValue": "350",
            "endValue": "400",
            "label": "3.50 or higher"
          }
        ]
      },
      {
        "tag": "CAT",
        "missingValue": "",
        "format": "Disc",
        "varName": "STEMMAJ",
        "label": "Major field of study with a focus on STEM fields",
        "element": [
          {
            "value": "1",
            "label": "Math/Computer/Sciences/Engineering/Technologies"
          },
          {
            "value": "2",
            "label": "Social/behavioral sciences"
          },
          {
            "value": "4",
            "label": "Non-STEM field"
          },
          {
            "value": "5",
            "label": "Undecided or not in a degree program"
          }
        ]
      }
    ]
  }
}

阅读 280

收藏
2020-07-27

共1个答案

小编典典

根据您在另一个答案中的评论,我现在可以了解您为什么感到困惑。您没有在问题中提到正在执行XML到JSON的转换。

如您所知,XML不像JSON那样具有“对象”或“数组”的概念。在XML中,所有内容都只是命名节点的集合。在确定某个东西应该是数组还是对象时,JSON.net会检查在同一级别上是否存在多个具有相同名称的节点。如果有的话,那显然是一个数组。但是,如果一个节点只有一个孩子,那就是模棱两可的。它可以是一个单项的数组,也可以只是一个简单的对象属性。默认情况下,Json.Net选择后者。如果XML中的结果数量可以从零到很多变化,那么转换为JSON时,处理起来会更加困难。

为了说明,请考虑以下XML。在其中,我们有三个不同的“集合”,每个集合中都有不同数量的“项目”。第一批只有一个孩子。第二个有两个,最后一个为空。

<root>
    <collection1>
        <item>
            <label>A</label>
            <value>1</value>
        </item>
    </collection1>
    <collection2>
        <item>
            <label>B</label>
            <value>2</value>
        </item>
        <item>
            <label>C</label>
            <value>3</value>
        </item>
    </collection2>
    <collection3 />
</root>

使用进行转换时JsonConvert.SerializeXmlNode(),我们得到以下JSON:

{
  "collection1": {
    "item": {
      "label": "A",
      "value": "1"
    }
  },
  "collection2": {
    "item": [
      {
        "label": "B",
        "value": "2"
      },
      {
        "label": "C",
        "value": "3"
      }
    ]
  },
  "collection3": null
}

请注意,在第一个集合中,项目已成为父集合对象的属性,而在第二种情况下,项目已放置在数组中,并且该数组已成item为父对象的属性值。(换句话说,实际项目在JSON结构中位于
下一层 !)最后一个集合根本没有item属性;它只包含一个属性。它的值为null

那么我们如何处理呢?我们真正需要的是一个帮助程序方法,该方法将处理所有这些不同的情况,并为我们提供JArray可以一致使用的项目(例如)的集合。

这是应该起作用的扩展方法:

public static class JsonHelper
{
    public static JArray ToJArray(this JToken token, string itemProperty)
    {
        if (token != null && token.Type != JTokenType.Null)
        {
            token = token[itemProperty];
            if (token != null)
            {
                if (token.Type == JTokenType.Array)
                {
                    return (JArray)token;
                }
                else
                {
                    return new JArray(token);
                }
            }
        }
        return new JArray();
    }
}

这是一个演示,演示了如何使用此帮助方法打印项目列表:

class Program
{
    static void Main(string[] args)
    {
        string json = @"
        {
          ""collection1"": {
            ""item"": {
              ""label"": ""A"",
              ""value"": ""1""
            }
          },
          ""collection2"": {
            ""item"": [
              {
                ""label"": ""B"",
                ""value"": ""2""
              },
              {
                ""label"": ""C"",
                ""value"": ""3""
              }
            ]
          },
          ""collection3"": null
        }";

        JObject root = JObject.Parse(json);

        DumpItems(root, "collection1");
        DumpItems(root, "collection2");
        DumpItems(root, "collection3");
    }

    private static void DumpItems(JToken token, string collectionName)
    {
        JArray array = token[collectionName].ToJArray("item");

        Console.WriteLine("Count of items in " + collectionName + ": " + array.Count);
        foreach (JToken item in array)
        {
            Console.WriteLine(item["label"] + ": " + item["value"]);
        }
    }
}

输出:

Count of items in collection1: 1
A: 1
Count of items in collection2: 2
B: 2
C: 3
Count of items in collection3: 0

回到原来的问题,您现在应该可以执行以下操作:

var count = token["rows"].ToJArray("component").Count;

并获得您期望的价值。

2020-07-27