How to correctly get array of array from Json in Unity

Viewed 160

I have JSON with an array of companies. They have an array of products with descriptions and product names. In Unity, I see everything except descriptions and product names. Is there something wrong with the product class?

json in unity

I have this JSON:

{
"company": [{
    "companyName": "samsung",       
    "products": [
        [{
            "productName": "samusung1",
            "productDescription": "description1"
        }],
        [{
            "productName": "samusung2",
            "productDescription": "description2"
        }],
        [{
            "productName": "samusung3",
            "productDescription": "description3"
        }],
        [{
            "productName": "samusung4",
            "productDescription": "description4"
        }]
    ]
}]

}

Class in Unity:

public class JsonReader : MonoBehaviour
{
public TextAsset companyJson;
[System.Serializable]
public class Company
{
    public string companyName;
    public Products[] products;
}

[System.Serializable]
public class Products
{
    public string productName;
    public string productDescription;
}
[System.Serializable]
public class CompanyList
{
    public Company[] company;
}

public CompanyList companyList = new CompanyList();

void Start()
{
    companyList = JsonUtility.FromJson<CompanyList>(companyJson.text);
} 
}
1 Answers

Each of your items e.g.

{
    "productName": "samusung4",
    "productDescription": "description4"
}

in your json is for some reason nested in individual arrays

[ 
    {
        "productName": "samusung4",
        "productDescription": "description4"
    }
]

In your JSON products is not an array of products, but rather an array of arrays of products.

So either your JSON should rather look like

{
"company": [{
    "companyName": "samsung",       
    "products": [
        {
            "productName": "samusung1",
            "productDescription": "description1"
        },
        {
            "productName": "samusung2",
            "productDescription": "description2"
        },
        {
            "productName": "samusung3",
            "productDescription": "description3"
        },
        {
            "productName": "samusung4",
            "productDescription": "description4"
        }
    ]
}]
}

Or your class structure needs to look like

[System.Serializable]
public class Company
{
    public string companyName;
    public Products[][] products;
}

[System.Serializable]
public class Products
{
    public string productName;
    public string productDescription;
}

[System.Serializable]
public class CompanyList
{
    public Company[] company;
}

But multidimensional arrays are not supported by the Unity built-in JsonUtility. You would need to use a third party library like Newtonsoft .Net JSON (there is a Unity Package via the package Manager in the newer versions).


The first solution (a different JSON) seems to make more sense anyway.

Related