Unity’s JsonUtility is very limited. It has the same limitations as the general script serialization. Furthermore you can only deserialize to actual classes, not generic dictionaries (especially since Unity’s serialization system does not support generics). That means a Json object need to be an actual class and the objects properties has to be represented with fields. This is impossible with your json data as you use “0” as key which can not be used as field name in a class. Furthermore it does not support an array as root element. So the top most object must be an object.
You essentially have two options:
- If you want to use Unity’s JsonUtility you have to redesign your Json data in a way it can be modelled with serializable classes inside Unity.
- Use a different Json library.
For example I’ve written the SimpleJSON library which is just one file to drop into your project. It has additional modules for directly converting common Unity types (vectors, quaternions, …) to a JSONObject or JSONArray. Though those aren’t needed in your case. SimpleJSON has been written to work outside of Unity in plain C#.
JSONNode node = JSON.Parse(dataAsJson);
Now you can directly access any value like this:
int armorLvl1 = node["1"]["Armor"];
There are several implicit casting operators which makes the use very easy. But it also has conversation properties like .AsInt
.
It uses strongly typed classes for the different json data types (object, array, number, boolean, null) and makes use of inheritance.
If you want to stick to Unity’s JsonUtility you may want to use something like this:
{
"Levels": [
{
"Armor": 1,
"Strenght": 1,
"Mana": 2,
"Power": 1,
"Health": 1
},
{
"Armor": 1,
"Strenght": 1
}
]
}
Now you would need classes like
[System.Serializable]
public class LevelBonus
{
public int Armor;
public int Strenght;
public int Mana;
public int Power;
public int Health;
}
[System.Serializable]
public class Bonus
{
public LevelBonus[] Levels;
}
With this json file and those classes you should be able to do this:
Bonus statsPerLevel = FileLoaderManager.instance.LoadJSONData<Bonus>("PlayerStats/level.json");
Since you don’t see the level in the json due to the array you may want to add another field inside each level object called “LevelIndex” or something like that and track the index of the element in the array that way, only for the human that is editing the file. Of course this has the risk of getting inconsistent and out of sync with the actual index if you add / remove objects in between und forget to adjust the values.