Amar.linsila
Amar.linsila

Reputation: 303

Get Length of JSON Array

I am using UnityWebRequest to get a query and parse it in JSON. Everything works as expected but here the node users is an array that is defined as below:

{
  "data": {
    "users": [
      {
        "id": "981d8432-c423-46e1-9124-5b5f111bd749",
      },
      {
        "id": "11cd2db5-3e6e-4363-b8e5-afd2a67a5333",
      }
   ]
}

Now I know that the array is 2 values but how do I make the for loop detect it by the length? Such that

using SimpleJSON;
...
...
void Start()
{

  JSONNode itemsData = JSON.Parse (request.downloadHandler.text);
  for(int i = 0;i<(LengthOfUsers); i++)
    {
      Debug.Log("\nIDs: "+ itemsData["data"]["users"][i]["id"]);
    }
}

Upvotes: 4

Views: 2575

Answers (4)

Eduard Hasanaj
Eduard Hasanaj

Reputation: 895

You can use JsonUtility provided by Unity. In order to deserialize above schema you need following classes

[System.Serializable]
public class User
{
    public string ID { get { return id; } }

    [SerializeField] private string id;
}

[System.Serializable]
public class UserCollection
{
    public User[] users;
}

JsonUtility.FromJson<UserCollection>(jsonText);

In the model class I suggest you to encapsulate attributes behind getters because sometimes we may need to deal with json that contains "_" or not idiomatic naming for c# class attributes and JsonUtility does not support custom attributes you are force to place weird names in the class.

Upvotes: 0

Amar.linsila
Amar.linsila

Reputation: 303

Thanks to Athanasios Kataras for the guidance. Instead of JSONNode, I used just simple var and then counted the length of the array users. The whole code is given below:

var parseJSON = JSON.Parse (request.downloadHandler.text);
var Count = parseJSON["data"]["users"].Count;
  for(int i = 0;i<Count; i++)
    {
      Debug.Log("\nIDs: "+ itemsData["data"]["users"][i]["id"]);
    }
}

Upvotes: 0

Jakob M&#248;ller
Jakob M&#248;ller

Reputation: 171

itemsData["data"]["users"].Length should do the trick in your case.

If you want, you could make your user-list into a variable:

JSONNode itemsData = JSON.Parse(request.downloadHandler.text);
var users = itemsData["data"]["users"]
for(int i = 0; i < (users.Length); i++)
{
    Debug.Log("\nIDs: "+ users[i]["id"]);
}

An alternative is to not worry about the length, by using a foreach:

JSONNode itemsData = JSON.Parse(request.downloadHandler.text);
foreach(var user in itemsData["data"]["users"])
{
    Debug.Log("\nIDs: "+ user["id"]);
}

Upvotes: 0

Athanasios Kataras
Athanasios Kataras

Reputation: 26430

Seems like JSonNode implements IEnumerator: https://wiki.unity3d.com/index.php/SimpleJSON

That means that you could in theory use the Linq extentions like this:

itemsData["data"]["users"].Count

Upvotes: 2

Related Questions