C# 获取数组长度 JSON.Net

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19025174/
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-10 13:55:57  来源:igfitidea点击:

Get Length of array JSON.Net

c#jsonjson.netxamarin

提问by Onno

How can I get the length of a JSON Array I get using json.net in C#? After sending a SOAP call I get a JSON string as answer, I use json.net to parse it.

如何获得在 C# 中使用 json.net 获得的 JSON 数组的长度?发送 SOAP 调用后,我得到一个 JSON 字符串作为答案,我使用 json.net 来解析它。

Example of the json I got:

我得到的 json 示例:

{"JSONObject": [
    {"Id":"ThisIsMyId","Value":"ThisIsMyValue"},
    {"Id":"ThisIsMyId2","Value":"ThisIsMyValue2"}
]}

And I parse it and write it in console:

我解析它并将其写入控制台:

var test = JObject.Parse (json);
Console.WriteLine ("Id: {0} Value: {1}", (string)test["JSONObject"][0]["Id"], (string)test["JSONObject"][0]["Value"]);

This works like a spell, only I don't know the length of the JSONObject, but I need to do it in a for loop. I only have no idea how I can get the length of test["JSONObject"]

这就像一个咒语,只是我不知道 的长度JSONObject,但我需要在 for 循环中进行。我只是不知道如何获得长度test["JSONObject"]

But something like test["JSONObject"].Lengthwould be too easy I guess :(..

test["JSONObject"].Length我想这样的事情太容易了:(..

采纳答案by musefan

You can cast the object to a JArrayand then use the Countproperty, like so:

您可以将对象强制转换为 a JArray,然后使用该Count属性,如下所示:

JArray items = (JArray)test["JSONObject"];
int length = items.Count;

You can then loop the items as follows:

然后,您可以按如下方式循环项目:

for (int i = 0; i < items.Count; i++)
{
    var item = (JObject)items[i];
    //do something with item
}


According to Onno (OP), you can also use the following:

根据 Onno (OP) 的说法,您还可以使用以下内容:

int length = test["JSONObject"].Count();

However, I have not personally confirmed that this will work

但是,我还没有亲自确认这会起作用

回答by ZaidRehman

You can use below line to get the length of JSON Array in .Net (JArray) .

您可以使用下面的行来获取 .Net( JArray)中 JSON 数组的长度。

 int length = ((JArray)test["jsonObject"]).Count;

回答by arul pushpam

Just try this:

试试这个:

var test= ((Newtonsoft.Json.Linq.JArray)json).Count;

回答by rafCalg

This worked for me supposing the json data is in a json file. In this case, .Length works but no intellisence is available:

假设 json 数据在 json 文件中,这对我有用。在这种情况下, .Length 有效,但没有可用的智能:

    public ActionResult Index()
    {
        string jsonFilePath = "C:\folder\jsonLength.json";
        var configFile = System.IO.File.ReadAllText(jsonFilePath);

        JavaScriptSerializer jss = new JavaScriptSerializer();
        var d = jss.Deserialize<dynamic>(configFile);

        var jsonObject = d["JSONObject"];
        int jsonObjectLength = jsonObject.Length;
        return View(jsonObjectLength);
    }