Unity Reading JSON Files

So, this one always seems to mess me around so I’m writing it up so I’ve got an easy reference for next time.

First we define the class we want to read the JSON into. This has to match to the format of the JSON (obviously) as it’s going to deserialize it. So, quick example might look like this: –

[Serializable]
public class ContentCollection
{
    public Content[] contents;
}

[Serializable]
public class Content
{
    public int id;
    public string stringStorage;
    public string moreStringStorage;
    public string[] arrayOfStrings;
    public bool boolStorage;
    public AnotherClass[] anotherArray;
}

[Serializable]
public class AnotherClass
{
    public int id;
    public string extraStringStorage;
}

The JSON to go with this would look something like this: –

{
    "content": [
    {
        "id": "1",
        "stringStorage": "First item",
        "moreStringStorage": "",
        "arrayOfStrings": [ "aString", "anotherString" ],
        "boolStorage": true,
        "anotherArray": [
        {
            "id": "89",
            "extraStringStorage": "something here"
        },
        {
            "id": "90",
            "extraStringStorage": ""
        }
        ]
    },
    {
        "id": "2",
        "stringStorage": "Second item",
        "moreStringStorage": "",
        "arrayOfStrings": [ "aString2", "anotherString2" ],
        "boolStorage": false,
        "anotherArray": [
        {
            "id": "91",
            "extraStringStorage": "something else here"
        },
        {
            "id": "92",
            "extraStringStorage": "some more here"
        }
        ]
    }
    ]
}

Now we read the JSON using a standard Unity JSON reader. ‘json’ in this example is just a json string of the above JSON content.

using UnityEngine;

ContentCollection content = JsonUtility.FromJson<ContentCollection>(json);

All content is read in from the json and stored in an array of ‘Content’ classes which can be easily referenced as needed.

Best to note that Unity JsonUtility does not work with arrays that are stored at the base level of the JSON. It just ignores them and causes great confusion. Multiple posts about it and there are a few wrapper classes available to solve the problem as follows: –

public class JsonHelper
{
    public static T[] GetJsonArray<T>(string json)
    {
        string newJson = "{ \"array\": " + json + "}";
        Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson);
        return wrapper.array;
    }

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

 

Hope it helps

 

 

 

 

 

 

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: