-1
[
    {"id": 1, "name": "danny_devito", "img": "/images/1"},
    {"id": 2, "name": "jim_carey", "img": "/images/2"},
    {"id": 3, "name": "tyler_1", "img": "/images/3"}
]
 [System.Serializable]
    public class Players {
        public int id;
        public string name;
        public string img;
    }

    [System.Serializable]
    public class PlayersArray {
        public Players[] playersData;
    }
string playersJson = File.ReadAllText(Application.dataPath + "/playersFile.json");
        PlayersArray loadedPlayerData = (PlayersArray)JsonUtility.FromJson<PlayersArray>(playersJson);

        Debug.Log("Danny Boy: " + loadedPlayerData.playersData[0].name);

I followed tons of tutorials and none of it works!

It gives me this error:

it gives me this error

Azhar Khan
  • 3,829
  • 11
  • 26
  • 32
  • 1
    Your JSON is array, but PlayersArray is object. – EylM Feb 01 '23 at 14:52
  • This is `JsonUtility` from [tag:unity3d], right? If so I don't think `JsonUtility.FromJson()` supports arrays as root containers, you may need to add some wrapper object. See [this answer](https://stackoverflow.com/a/36244111/3744182) by [Programmer](https://stackoverflow.com/users/3785314/programmer) to [Serialize and Deserialize Json and Json Array in Unity](https://stackoverflow.com/q/36239705/3744182). In fact I think your question is a duplicate, agree? – dbc Feb 01 '23 at 17:15
  • Alternatively, as noted in the answer above, Json.NET is now officially supported by Unity, you may get it from here: https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@3.0/manual/index.html. With Json.NET you can do `var players = JsonConvert.DeserializeObject>(playersJson);` – dbc Feb 01 '23 at 17:17

1 Answers1

0

You're trying to deserialize an object. But the JSON you show isn't an object. It's an array. Deserialize it into a collection:

var loadedPlayerData = JsonUtility.FromJson<List<Players>>(playersJson);

Or even just an array:

var loadedPlayerData = JsonUtility.FromJson<Players[]>(playersJson);

As an aside... Names are important. Players is a misleading name for a player. The class should be called Player instead.


Additionally, this class might not deserialize at all, depending on how the JSON serializer works. They tend to use properties, not fields. You'll likely want to use properties anyway:

public class Players {
    public int id { get; set; }
    public string name { get; set; }
    public string img { get; set; }
}

For further improvements, you will probably also want to capitalize the property names. The JSON serializer might be case-sensitive (I don't think they tend to be by default, but it's worth testing) and you may need to add attributes to the properties to specify their names in the JSON. But just to get the code working, at the very least you'll most likely need properties here instead of fields.

David
  • 208,112
  • 36
  • 198
  • 279