I have been trying to make a sample of loading in JSON array and can't seem to get it working. I get no errors but I can't seem to get any data, The JSON file Code (CSharp): { "Player": [ { "name": "Warrior", "health": 100, "mana": 20 }, { "name": "Wizard", "health": 40, "mana": 80 }, { "name": "Healer", "health": 100, "mana": 120 } ] } and here is the code I am using. I also left a few things I tried in and commented out Code (CSharp): public TextAsset textJSON; [System.Serializable] public class Player { public string name; public string health; public int mana; } [System.Serializable] public class PlayerList { public Player[] player; } public PlayerList myPlayerList = new PlayerList(); // Start is called before the first frame update void Start() { myPlayerList = JsonUtility.FromJson<PlayerList>(textJSON.text); //myPlayerList = (PlayerList)JsonUtility.FromJson(textJSON.text,typeof(PlayerList)); //JsonUtility.FromJsonOverwrite(textJSON.text, myPlayerList);
Case sensitivity issue detected ^^ Your json text reads: Code (CSharp): { "Player": [ { while the class you created to represent your root object reads Code (CSharp): public Player[] player; "player" and "Player" are not the same thing.
What Bunny says above... I also highly suggest staying away from Unity's JSON "tiny lite" package. It's really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes. Instead grab Newtonsoft JSON .NET off the asset store for free, as it is way better. PS: for folks howling about how it will "add too much size" to your game, JSON .NET is like 307k in size, and it has the important advantage that it actually works.
It was simply a lack of understanding on my part. I thought it was meant to be Player with the cap P. Changing to lower case and it works fine. Honestly I was just curious how to do it since I often just read in text files (like I find a file online with 1000 names and read it in to apply to NPC's etc). Some said why don't you use JSON, so I thought I would give it a go! The silent fail did suck!
Thanks but I am more of a designer who likes to be able to make things by myself. Still a bit embarrassed how simple the issue was, but glad I asked because with no error I would have never got this. I had a look at that asset, it looks like a direct replacement using the same namespace which is awesome!