Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...