How to load an array with JsonUtility?

If you use this free Unity-compatible fork of Newtonsoft’s JSON.NET, then everything just works as you’d expect. There’s a good reason even Microsoft recommends using this third-party solution rather than .NET’s built-in options!

PlayerStats[] statArray = JsonConvert.DeserializeObject<PlayerStats[]>(json);
3 Likes

Is it working ?
Its not Working for me :confused:

1 Like

Thanks, it work!!!

It’s helpful, but how to make a file like ur file [PlayerStats].

hey everyone! - i’m having a bit of trouble on the deserializing front. here’s the basic array format in text file. note that my code doesn’t contain the indents or line breaks - i assume that’s not important? i’m breaking it up here so you can see the basic structure:

{
"SavedLayer":[
{
"layerName":"Layer_0",
"instrumentNumber":0,
"seqLength":7,
"timeDivision":8,
"gateTime":0.30000001192092898,
"noteRowAssign":[30,42,44,46,47,59,63,80]
},
{"layerName":"Layer_1",
"instrumentNumber":1,
"seqLength":8,
"timeDivision":16,
"gateTime":0.30000001192092898,
"noteRowAssign":[40,42,43,44,46,48,49,51]
},
]

}

i’m trying to retrieve it like this:

string AllTheData=File.ReadAllText(filename);
SavedLayer[] data=JsonHelper.getJsonArray<SavedLayer>(AllTheData);
Debug.Log(data[0]);

SavedLayer is the basic class i created to store each object’s data in JSON. it validates in JSON Lint as well. however if i try to get the first object in the array using this method, i get ‘unexpected node type’ and a Null Ref on the Debug.Log statement.

any clue what i’m doing wrong here?

1 Like

ffleurey’s JsonHelper code expects the top-level array to be called ‘array’, not ‘SavedLayer.’

1 Like

hmm - well looking at it after some sleep it actually looks like it wraps the '['and ‘]’ that begin and end the array with ‘{ array:’ and ‘}’. which technically means i don’t have to bother as long as my array begins and ends with square brackets. but i’m still having a lot of trouble understanding the deserialization process. i went back to the Scripting API for retrieving JSON data (https://docs.unity3d.com/ScriptReference/JsonUtility.FromJson.html). i’ve given it a try, but my code is definitely not working. the main bit is here:

    public static DataManager.SavedLayer readLayerJSON(string dataString)
    {
        string AllTheData = File.ReadAllText(DataManager.filenamePath());
        allLayers = JsonHelper.getJsonArray<DataManager.SavedLayer>(AllTheData);

        for (int count=0; count <8; count++)
        {
            return JsonUtility.FromJson<DataManager.SavedLayer>(dataString);
        }

    }

i’m obviously getting confused about what all the data(aka AllTheData) is vs parsing out each individual JSON object within the data. is it possible to retrieve all data for all objects at once without having to loop? this code fails but all my fixes so far aren’t doing the trick. i want to copy each Layer object’s JSON data to each element of allLayers, which is an array of DataManager.SavedLayer classes. assistance appreciated!

ADD THAT INTO DOCUMENTATION !!!

There is no mention about properties in docs. So you can save developers’ time and Karma of unitech :smile:

4 Likes

It works like charm ,man (Y) hope it wouldn’t fail in any case Thanku

hey, I just want to refer this issue to this thread, but I have an issue on hololens with it.

Anyway thx ffleure → good job :slight_smile:

I use both SimpleJson and JsonUtility

You’re an HERO elektronische!
I confirm this works just fine and using lists instead of arrays brings only advantages to me!

This is how the official unity documentation should look like:

JsonUtility

class in UnityEngine

Other Versions

Description
Utility functions for working with JSON data.
YO FOLKS, arrays DO NOT work with this utility!!! Just use Lists and FromJsonOverwrite to store lists of data.

1 Like

Absolutely right^

However, if you do need/want to use arrays and don’t want to/can change the response from the server you could just wrap your json array inside an object. Then you can use the Wrapper method discussed before.

So if you have this:

[
    {
        "id": "1",
        "name": "foo"
    },
    {
        "id": "2",
        "name": "bar"
    },
    {
        "id": "3",
        "name": "baz"
    }
]

You want to get something like this:

{
    "items": [
        {
            "id": "1",
            "name": "foo"
        },
        {
            "id": "2",
            "name": "bar"
        },
        {
            "id": "3",
            "name": "baz"
        }
    ]
}

Here’s my updated JsonHelper.cs https://gist.github.com/halzate93/77e2011123b6af2541074e2a9edd5fc0

using System;
using UnityEngine;

    public static class JsonHelper
    {
        public static T[] FromJson<T>(string jsonArray)
        {
            jsonArray = WrapArray (jsonArray);
            return FromJsonWrapped<T> (jsonArray);
        }

        public static T[] FromJsonWrapped<T> (string jsonObject)
        {
            Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(jsonObject);
            return wrapper.items;
        }

        private static string WrapArray (string jsonArray)
        {
            return "{ \"items\": " + jsonArray + "}";
        }

        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);
        }

        [Serializable]
        private class Wrapper<T>
        {
            public T[] items;
        }
    }
4 Likes

Hi all, thank you for sharing the information.
I use JavaScript, but did not find any useful example of how to use JsonUtility.FromJson in JavaScript.
In case anyone is looking for how to deserialize (convert) JSON with array in Unity using JavaScript I’ve made an example:

// Unity data classses
public class Ball { // this is required in both cases: single and array
    public var size : float;
    public var color : String;
    public var weight : int;
}

public class Balls { // this is required only in case of array
    public var allBalls : Ball[];
}

// Get JSON data
var ballJson : String = '{"size":1,"color":"red","weight":2}';

// Instantiate data from JSON
var oneBall : Ball = JsonUtility.FromJson.<Ball>(ballJson);

// Use the data
Debug.Log('RED BALL:\nCOLOR: '+oneBall.color+'\nSIZE: '+oneBall.size+'\nWEIGHT: '+oneBall.weight);

// Get JSON data
var ballsJson : String = '{"allBalls":[{"size":"1f","color":"red","weight":2},{"size":"1.2f","color":"blue","weight":3},{"size":0.9,"color":"green","weight":5}]}';

// Instantiate data from JSON with array
var manyBalls : Balls = JsonUtility.FromJson.<Balls>(ballsJson);

// Use the data
for (var i = 0; i < manyBalls.allBalls.length; i++) {
    Debug.Log('#'+i+') BALL:\nCOLOR: '+manyBalls.allBalls[i].color+'\nSIZE: '+manyBalls.allBalls[i].size+'\nWEIGHT: '+manyBalls.allBalls[i].weight);
}

You can use JsonUtility.FromJson(ballJson, Ball) instead of JsonUtility.FromJson.<Ball>(ballJson) if you like.

Result looks like:
3046638--228447--ScreenShot.PNG

1 Like

hi @halzate93 thanks for your codes, but your FromJson function seems doesn’t work for me. It gives me NullReferenceException.

I have a simple code like below using your FromJson function :

void Start () {
        TextAsset data = Resources.Load("Creature") as TextAsset;
        Debug.Log(data.name);
        Debug.Log(data.text);
        string dataText = data.ToString();
        Creature[] creatures = JsonHelper.FromJson<Creature>(dataText);
        Debug.Log(creatures.Length);
        for (int i = 0; i < creatures.Length; i++) {
            Debug.Log(creatures[i].Name);
        }
    }

my json file structure is like this :

[
    {
        "Name" : "ARC",
        "Level" : "7",
        "Stats" : [4,7]
    },
    {
        "Name" : "ARS",
        "Level" : "1",
        "Stats" : [3,1]
    }
]

Read Post #15 and Post #33 in this thread. You need to use a wrapper around your json data to make it accessible.

Slightly off topic. I’ve enjoyed reading through this thread, and it’s helped me to successfully read and write toJson (using both lists and arrays). I don’t suppose anyone here has hit the obstacle of derived classes not serializing correctly? All my data gets serialized as if it was the base type only

{
“test1”: “first string”,
“test2”: “second string”,
“test3” :
[
{
“title” : "Red ",
“image” : “Image Url”
},
{
“title” : "Green ",
“image” : “Image Url”
},
{
“title” : "Blue ",
“image” : “Image Url”
},
{
“title” : "Yellow ",
“image” : “Image Url”
}
]
}

hi all i am confusing that i need to access the first value of the “buttons” array from this json and then pick up the first value which is “Red” so how can i access this value can you give me some detailing example because i am confused that how to access the array from json in unity i need to debugging the “title” object from the array.

please can you help with some array objects in detaling .

Have a look at this:

It is rather frustrating that this is supposedly on the list of thing to fix for like 2 years now. I am finding myself in the same boat here because I need to ingest data coming from a server that I have no control over, and all the data is returned in top level arrays :frowning: