Bunny83 / SimpleJSON

A simple JSON parser in C#
MIT License
735 stars 294 forks source link

How to use as_array and get array size? #54

Open CengizPoyraz opened 1 year ago

CengizPoyraz commented 1 year ago

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 commented 1 year ago

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