JSON计数只返回1而不是2



我有这行代码(它总是返回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"
          }
        ]
      }
    ]
  }
}

根据您在另一个答案中的评论,我现在可以理解您为什么感到困惑了。您在问题中没有提到您正在进行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属性;而是具有值CCD_ 4。

那么我们该如何应对呢?我们真正需要的是一个助手方法,它将处理所有这些不同的情况,并给我们一个可以一致处理的项目集合(例如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;

并获得您期望的价值。

以下代码:

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

会给你正确的答案。

我测试了这个代码:

var token = JObject.Parse(...your pasted JSON...);
int rowsCount = token["rows"]["component"].Count();

您应该粘贴http://jsonlint.com/用于缩进,这可能会有所帮助。

问题是因为。。。好吧,它是一个。"rows"json是"rows": {,意思是。。。这个名字太可怕了。此处的行是一个对象(请参阅{)。它不是一个数组。只有一个。您想要的可能是行中的组件。也许json生成是错误的,但其中一个是正确的答案。

相关内容

  • 没有找到相关文章

最新更新