使用 C# 中的 Json.NET 计算 JSON 字符串中的元素数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10001142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:04:52  来源:igfitidea点击:

Count Number of Elements in JSON string with Json.NET in C#

c#jsonjson.net

提问by Brent Barbata

I have a JSON string that looks like this:

我有一个如下所示的 JSON 字符串:

{
"package1": {
    "type": "envelope",
    "quantity": 1,
    "length": 6,
    "width": 1,
    "height": 4
},
"package2": {
    "type": "box",
    "quantity": 2,
    "length": 9,
    "width": 9,
    "height": 9
}
}

I'm using the Json.NET LINQ to JSON functionality to handle my JSON string, but I'm wondering how I can find the total number of nodes/elements/keys (I'm not really sure what to call them) in my string. For example, the above string has package1 and package2 so I'm wondering how I can get it to return the integer 2. Sometimes I might only have one package, in which case, I'd like it to return the integer 1. Other times I might have 20 packages (in that case I'd like it to return 20).

我正在使用 Json.NET LINQ to JSON 功能来处理我的 JSON 字符串,但我想知道如何在我的细绳。例如,上面的字符串有 package1 和 package2,所以我想知道如何让它返回整数 2。有时我可能只有一个包,在这种情况下,我希望它返回整数 1。其他有时我可能有 20 个包裹(在这种情况下,我希望它返回 20 个)。

My JObject looks like this:

我的 JObject 看起来像这样:

JObject o = JObject.Parse(myJsonString);

Any ideas? Thanks for any help.

有任何想法吗?谢谢你的帮助。

采纳答案by L.B

JObject jObj = (JObject)JsonConvert.DeserializeObject(myJsonString);
int count = jObj.Count;

BONUS:

奖金:

dynamic jObj = JsonConvert.DeserializeObject(myJsonString);

foreach (var package in jObj)
{
    Console.WriteLine("{0} {1}", package.First.type, package.First.quantity);
}

回答by Har

in JQuery $.ajax you will receive an array, traverse through the elements and get the sum.

在 JQuery $.ajax 中,您将收到一个数组,遍历元素并获得总和。

回答by Thymine

Recursive version (count all properties with primitive values)

递归版本(计算所有具有原始值的属性)

Came across this question trying to google for a recursive count of JObject values, didn't find many other questions, so figured I'd add what I came up with to this question as well

遇到这个问题试图用谷歌搜索 JObject 值的递归计数,没有找到很多其他问题,所以我想我也会在这个问题中添加我想出的东西

int CountJTokenProperties(JToken token)
{
    var sum = 0;

    if (token.Type == JTokenType.Object)
    {
        foreach (var child in token.Value<JObject>())
        {
            sum += CountJTokenProperties(child.Value);
        }
    }
    else if (token.Type == JTokenType.Array)
    {
        foreach (var child in token.Value<JArray>())
        {
            sum += CountJTokenProperties(child);
        }
    }
    else
    {
        sum += 1;
    }

    return sum;
}

There might be a better alternative to .Value<JObject>()and .Value<JArray>(), but this seems to be working.

有可能是一个更好的选择.Value<JObject>().Value<JArray>(),但是这似乎是工作。

And specifically I wanted this for a nunit test that had variable sample data, and wanted to make sure it deserialized correctly. Decided that an easy way to check would be how many non-default values there were on the C# object, and JsonConvert has that ability:

特别是我想要这个用于具有可变样本数据的 nunit 测试,并希望确保它正确反序列化。决定一种简单的检查方法是 C# 对象上有多少非默认值,而 JsonConvert 具有这种能力:

public int CountNonDefaultProperties(object obj)
{
    // Let JsonConvert do the work of stripping out default values
    var serialized = JsonConvert.SerializeObject(obj, new JsonSerializerSettings
    {
        DefaultValueHandling = DefaultValueHandling.Ignore
    });

    // Recurse into the json structure, which is much simpler than C# Object structure
    var jObj = JObject.Parse(serialized);

    return CountJTokenProperties(jObj);
}

Note that DefaultValueHandling.Ignorekeeps default values that are part of arrays, so if you wanted that feature you'd need to count the array items in a different way or something, this activity is left to the reader

请注意,DefaultValueHandling.Ignore保留作为数组一部分的默认值,因此如果您想要该功能,则需要以不同的方式或其他方式计算数组项,此活动留给读者

https://dotnetfiddle.net/XIZCvh

https://dotnetfiddle.net/XIZCvh

回答by RajN

With Cinchoo ETL- an open source library, you can do the node count easily with less memory overhead, as it is using streaming approach to parse the input. Hence it can handle large file as well.

使用Cinchoo ETL——一个开源库,你可以用更少的内存开销轻松地进行节点计数,因为它使用流方法来解析输入。因此它也可以处理大文件。

string json = @"{
""package1"": {
""type"": ""envelope"",
""quantity"": 1,
""length"": 6,
""width"": 1,
""height"": 4
},
""package2"": {
""type"": ""box"",
""quantity"": 2,
""length"": 9,
""width"": 9,
""height"": 9
}
}";

using (var p = ChoJSONReader.LoadText(json).WithJSONPath("$.*"))
{
    Console.WriteLine(p.Count());
}

Hope it helps.

希望能帮助到你。

回答by DerpyCoder

 string json= "{
"package1": {
"type": "envelope",
"quantity": 1,
"length": 6,
"width": 1,
"height": 4
 },
 "package2": {
 "type": "box",
 "quantity": 2,
 "length": 9,
 "width": 9,
 "height": 9
 }
 }"; 

 dynamic stuff;
 int count;
 stuff = JsonConvert.DeserializeObject(json);
 foreach(JProperty s in stuff){

  count++;
  }

  Console.WriteLine(count.ToString());

If the Count property does not work out for you, try this instead. Ensure that your C# version is 4.0 or higher, as the dynamic keyword was added at that time.

如果 Count 属性对您不起作用,请改用此方法。确保您的 C# 版本为 4.0 或更高版本,因为当时添加了 dynamic 关键字。