JSON计数仅返回1而不是2

时间:2013-11-22 23:41:20

标签: c# .net json json.net

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

3 个答案:

答案 0 :(得分:4)

根据你在另一个答案中的评论,我现在可以看到为什么你感到困惑。您没有提到您在问题中正在进行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;

并获得您期望的价值。

答案 1 :(得分:1)

以下代码:

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

会给你正确答案。

我测试了这段代码:

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

答案 2 :(得分:0)

您应粘贴http://jsonlint.com/以获取有用的缩进信息。

问题是因为......它就是一个。 “行”json是"rows": {,这意味着......这是一个可怕的名字。这里的行是一个对象(参见{)。它不是一个数组。只有一个。你想要的可能是行内部的组件。也许json一代是错误的,但一个是正确的答案。