问题描述
如何获取在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的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!