问题描述
如何获得在 C# 中使用 json.net 获得的 JSON 数组的长度?发送 SOAP 调用后,我得到一个 JSON 字符串作为答案,我使用 json.net 对其进行解析.
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.
我得到的json示例:
Example of the json I got:
{"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"]);
这就像一个咒语,只是我不知道 JSONObject
的长度,但我需要在 for 循环中进行.我只是不知道如何获得 test["JSONObject"]
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"]
但是我想像 test["JSONObject"].Length
这样的东西太简单了 :(..
But something like test["JSONObject"].Length
would be too easy I guess :(..
推荐答案
您可以将对象强制转换为 JArray
,然后使用 Count
属性,如下所示:
You can cast the object to a JArray
and then use the Count
property, like so:
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
}
根据 Onno (OP),您还可以使用以下内容:
According to Onno (OP), you can also use the following:
int length = test["JSONObject"].Count();
但是,我个人还没有确认这会起作用
However, I have not personally confirmed that this will work
这篇关于获取数组长度 JSON.Net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!