JSON只计算返回1而不是2 [英] JSON count only returns 1 instead of 2

查看:160
本文介绍了JSON只计算返回1而不是2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  INT rowsCount =令牌[行。计数(); 



在哪里令牌[行]为:

  {
成分:
{
标签:CUT,
missingValue:,
格式:续,
的varName:政府采购协定,
标签:平均成绩,
元素:
{
在startValue:1,
endValue值:249,
标签:低于2.50
},
{
在startValue:250,
endValue值:299,
标签:2.50 - 2.99
},
{
在startValue:300,
endValue值:349,
标签:3.00 - 3.49
},
{
在startValue:350,
endValue值:400,
标签:3.50或更高版本
}
]
},
{
标签:CAT,
missingValue:,
格式:光盘,
的varName:STEMMAJ ,
标签:重点是STEM领域研究的主要领域,
元素:
{
值:1,
标签:数学/计算机/科学/工程/技术
},
{
值:2,
标签:社会/行为科学
},
{
值:4,
标签:非干田
},
{
值:5,
标签:未定或没有学位课程
}
]
}
[
}

我想获得部件数量的计数。

这不工作之一:

 令牌[行] [ 组件] COUNT()。 



整个JSON是在这里:

  {
版本:1.0,
createdBy:调压变压器V1.0,
测试:OHOH,
DSNumber:{
值:82
},
称号:{
值:
},
注脚:{
值:
},
flagRSE:{
值:30,50,
符号:,!!
},
重:{
类型:0,
的varName:WTA000,
标签:weight_var
},
过滤器:{
FILTER_1:{
成分:{
的varName:JOBEARN2,
过滤式:范围,
格式:续,
标签:工作:收入来自工作,而报名参加(包括勤工助学),
元素 :{
在startValue:1,
endValue值:,
标签:X - GT; = 1
}
}
},
filter_2:{
成分:{
的varName:JOBROLE2,
过滤式:DIST,
格式:光盘,
标签:招聘:为学生或员工主要作用(包括勤工助学),
元素:{
的价值:1,
标签:一个学生合作,以满足支出
}
}
}
},
柱 :{
成分:{
标签:CAT,
missingValue:4,5,6,7,8,9,10,13,14, 15,16,17,18,19,20,21,22,23,-3,
格式:光盘,
的varName:MAJORS23,
标签:实地研究:本科(23类),
元素:
{
值:0,
标签: 未定
},
{
值:1,
标签:计算机与信息科学
},
{
值:2,
标签:工程与工程技术
},
{
值:3
标签:生物和物理科学,科学技术
},
{
值:11,
标签:个人和消费者服务
},
{
值:12,
标签:制造,施工,维修和放大器;交通
}
]
}
},
行:{
成分:
{
标签:CUT,
missingValue:,
格式:续,
的varName:政府采购协定,
标签 :平均成绩,
元素:
{
在startValue:1,
endValue值:249,
标签:低于2.50
},
{
在startValue:250,
endValue值:299,
标签 2.50 - 2.99
},
{
在startValue:300,
endValue值:349,
标签: 3.00 - 3.49
},
{
在startValue:350,
endValue值:400,
标签:3.50或较高的
}
]
},
{
标签:CAT,
missingValue:,
格式:光盘,
的varName:STEMMAJ,
标签:重点是STEM领域研究的主要领域,
元素:
{
值:1,
标签:数学/计算机/科学/工程/技术
},
{
值:2,
标签:社会/行为科学
},
{
值:4,
标签:非干田
},
{
值:5,
标签:未定或没有学位课程
}
]
}
]
}
}


解决方案

根据另一种回答您的意见,我现在可以明白为什么你感到困惑。你没有提到你正在做XML来在你的问题JSON的转变。<​​/ p>

正如我敢肯定,大家都知道,XML不具备的概念对象或阵列像JSON一样。在XML中,一切都只是一个命名节点的集合。当某物是否应该是一个数组或一个对象决定,JSON.net看是否有在使用相同的名称相同的水平的多个节点。如果有,这些是清楚的阵列。但是,如果一个节点只有一个子,它是不明确的。它可能是一个项目的阵列,或者它可能只是一个简单的对象属性。缺省情况下,Json.Net选择了后者。如果你的XML结果的数量可以从零到许多各不相同,这可以让事情变得更难以处理,当转换成JSON。



要说明这一点,考虑以下XML。在这里面,我们有三个不同的集合,每个都有不同数量的它项目。第一个集合只有一个子女; 。第二个有两个,最后一个是空的。



 <根和GT; 
< collection1>
<项目>
<标签> A< /标签>
<价值> 1 LT; /值>
< /项目>
< / collection1>
< collection2>
<项目>
<标签> B< /标签>
<价值> 2'; /值>
< /项目>
<项目>
<标签> C< /标签>
< VALUE>第3版; /值>
< /项目>
< / collection2>
< collection3 />
< /根>

在使用的 JsonConvert.SerializeXmlNode() ,我们得到这个JSON:

  {
collection1:{
项:{
标签:A,
值:1
}
},
collection2:{
项:
{
标签:b,
值:2
},
{
标签:C,
值:3
}
]
},
collection3:空
}

注意,在第一集合中,该项目已成为父集合对象的属性,而在第二种情况下,物品被放置在阵列中,并且该阵列已成为值父对象上的项目属性。 (换句话说,实际项目的一个级别进一步向下的在JSON结构!)最后一次采集没有一个项目酒店在所有;它的值为代替。



那么,我们如何面对呢?我们真正需要的是一个辅助方法,将处理所有这些不同的情况下,给我们带回项目的集合(如 JArray ),我们可以一致地工作。



下面是应该工作的扩展方法:

 公共静态类JsonHelper 
{
公共静态JArray ToJArray(这JToken道理,串itemProperty)
{
如果(标记=空&安培;!&安培;!token.Type = JTokenType.Null)
{
记号=记号[itemProperty]
如果(令牌!= NULL)
{
如果(token.Type == JTokenType.Array)
{
回报(JArray)令牌;
}
,否则
{
返回新JArray(令牌);
}
}
}
返回新JArray();
}
}

下面是展示我们如何使用这个辅助方法演示打印出的项目清单:

 类节目
{
静态无效的主要(字符串[]参数)
{
串JSON = @
{
collection1:{
,项:{
,标签:A,
的价值:1
}
},
collection2:{
项目:
{
标签:b,
的价值:2
},
{
标签:C,
的价值:3
}
]
} ,
collection3:空
};

JObject根= JObject.Parse(JSON);

DumpItems(根,collection1);
DumpItems(根,collection2);
DumpItems(根,collection3);
}

私有静态无效DumpItems(JToken道理,串集合名)
{
JArray阵列=令牌[集合名] .ToJArray(项目);

Console.WriteLine(+集合名+中的项目的计数:+ array.Count);
的foreach(数组JToken项)
{
Console.WriteLine(项目[标签] +:+项目[价值]);
}
}
}



输出:



 在collection1项目数:1 
答:2
A:在collection2项目1
计数:2
C:0

展望:在collection3项目3
计数回到你原来的问题,你现在应该能够做到这一点:

 变种数=令牌[行] ToJArray (部件)计数; 

和得到你所期望的价值。


I have this line of code (which always returns 1):

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

Where token["rows"] is:

    {
  "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"
        }
      ]
    }
  ]
}

I want to get a count of the number of components.

This isn't working either:

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

The entire JSON is here:

    {
  "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"
          }
        ]
      }
    ]
  }
}

解决方案

Based on your comments in another answer, I can see now why you are confused. You did not mention that you are doing XML to JSON transformation in your question.

As I'm sure you are aware, XML doesn't have the concept of an "object" or an "array" like JSON does. In XML, everything is just a collection of named nodes. When deciding on whether something should be an array or an object, JSON.net looks at whether there are multiple nodes at the same level with the same name. If there are, those are clearly an array. But if a node has only a single child, it is ambiguous. It could be an array of one item, or it could be just a simple object property. By default, Json.Net chooses the latter. If the number of results in your XML can vary from zero to many, this can make things more difficult to deal with when converted to JSON.

To illustrate, consider the following XML. In it, we have three different "collections", each with a different number of "items" in it. The first collection has just one child; the second has two, and the last is empty.

<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>

When transformed using JsonConvert.SerializeXmlNode(), we get this JSON:

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

Notice that in the first collection, the item has become a property of the parent collection object, while in the second case, the items are placed in an array, and that array has become the value of an item property on the parent object. (In other words, the actual items are one level further down in the JSON structure!) The last collection does not have an item property at all; it has a value of null instead.

So how do we deal with this? What we really need is a helper method that will handle all these varying cases and give us back a collection of items (e.g. a JArray) that we can work with consistently.

Here's an extension method that should work:

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();
    }
}

Here's a demo showing how we can use this helper method to print out the lists of items:

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"]);
        }
    }
}

Output:

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

Going back to your original question, you should now be able to do this:

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

and get the value you expect.

这篇关于JSON只计算返回1而不是2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆