Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use as_array and get array size? #54

Open
CengizPoyraz opened this issue Mar 18, 2023 · 1 comment
Open

How to use as_array and get array size? #54

CengizPoyraz opened this issue Mar 18, 2023 · 1 comment

Comments

@CengizPoyraz
Copy link

Hi,

I could not find how to use as_array and get the array size if I have out["BankList"] like {"BankList":[{"Name": "Bank 1"}, {"Name": "Bank 2"}]. better to see some examples if possible.

@Bunny83
Copy link
Owner

Bunny83 commented Mar 18, 2023

You don't need to use AsArray in almost all cases as the JSONNode base class usually provides everything you need. You can use the Count property to get the number of elements of an array. So with the json you have in your example you can do:

JSONNode node = JSON.Parse(yourJson);
int count = node["BankList"].Count;
for(int i = 0; i < count; i++)
{
    string name = node["BankList"][i]["Name"];
}

Of course you can also use the enumerator of the JSONNode class like this:

JSONNode node = JSON.Parse(yourJson);
foreach(JSONNode bank in node["BankList"])
{
    string name = bank["Name"];
}

Be warned that you can not use var in the for each loop. Well you can but the actual enumerable uses a KeyValuePair as element. So this would do the same:

JSONNode node = JSON.Parse(yourJson);
foreach(var kv in node["BankList"])
{
    string name = kv.Value["Name"];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants