0

I'm trying to deserialize a JSON string following this question, but im only getting "Object reference not set to an instance of an object" at line 14 of MenuItemBrands.cs (Debug.log(...))

Can anyone help me?

brands.json

{"brands":[{"id":1,"name":"test1","logo_img":"test.jpg"},{"id":2,"name":"test2","logo_img":"test.jpg"}]}

Brands.cs

[System.Serializable]
public class Brand
{
    public int id;
    public string name;
    public string logo_img;
}

JsonHelper.cs

public static class JsonHelper
{
    public static T[] FromJson<T>(string json)
    {
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
        return wrapper.Items;
    }

    public static string ToJson<T>(T[] array)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper);
    }

    public static string ToJson<T>(T[] array, bool prettyPrint)
    {
        Wrapper<T> wrapper = new Wrapper<T>();
        wrapper.Items = array;
        return JsonUtility.ToJson(wrapper, prettyPrint);
    }

    [System.Serializable]
    private class Wrapper<T>
    {
        public T[] Items;
    }
}

MenuItemBrands.cs

public class MenuItem3dBrands : MonoBehaviour
{

    private void Start()
    {
        LoadBrands();
    }

    protected void LoadBrands()
    {
        Brand[] brand = JsonHelper.FromJson<Brand>(Resources.Load<TextAsset>("brands").text);
        Debug.Log(brand[0].id);
    }

}
Chico3001
  • 1,513
  • 1
  • 15
  • 32
  • Put a breakpoint on the first line of `LoadBrands`. Run to the breakpoint. When you hit the breakpoint, type in `?Resources.Load("brands").text` in the `Immediate Window`. What is shown as a result there? – mjwills Apr 25 '20 at 06:29
  • https://app.quicktype.io?share=vxxHkirBmSDJ87rfOIuF The issue is likely that you are likely to deserialise JSON that _isn't_ an array of `Brand` to an array of `Brand`. https://app.quicktype.io?share=vxxHkirBmSDJ87rfOIuF shows you what you _should_ be deserialising to (i.e. `Welcome` with a `Brands` property inside it). – mjwills Apr 25 '20 at 06:32

0 Answers0