Sameer Hussain
Sameer Hussain

Reputation: 2561

How to get sub array using JsonUtility in unity

This is the JSON I have:

{"data":[{"id":1,"layoutLabel":"Sameer Non Custom","orbNumber":"["0","1","2","3"]"},
{"id":2,"layoutLabel":"Samer Custom","orbNumber":"["2","3","4","5"]"}],"status":200}

Here are my C# classes in unity to Deserialise it:

[System.Serializable]
class GetLayoutsResult
{
    public List<LayoutData> data;
    public int status;
}

[System.Serializable]
class LayoutData
{
    public int id;
    public string layoutLabel;
    public string [] orbNumber;
}

Here is the code to deserialise it:

     GetLayoutsResult P = JsonUtility.FromJson<GetLayoutsResult>(w.text);
        if (P.status == 200)
        {
            for (int i = 0; i < P.data.Count; i++)
            {
               Debug.Log(layoutEditButtonScript.layoutName + " " + P.data[i].positionX[0])
            }
 }

I don't get positionX array in this. I get an index array error instead. Can anyone help me deserialise a sub array in unity ?

Upvotes: 1

Views: 365

Answers (1)

turnipinrut
turnipinrut

Reputation: 624

The problem is that your json is incorrectly formatted.

This:

"orbNumber": "["0", "1", "2", "3"]"

Should be this:

"orbNumber": ["0", "1", "2", "3"]

No need to put quotes around an array.

Also, you need to rename positionX to orbNumber in your model class.

Upvotes: 3

Related Questions