1

I'm having an issue with Unity's FromJson method. From the error I'm assuming that there's something wrong with the JSON that I wrote, but I can't for the life of me figure out what it is. First, here's the error

ArgumentException: JSON parse error: Invalid value.
UnityEngine.JsonUtility.FromJson[ShipTypes] (System.String json) (at C:/buildslave/unity/build/artifacts/generated/bindings_old/common/JSONSerialize/JsonUtilityBindings.gen.cs:25)
DataLoader.LoadShipsFromJSON () (at Assets/Scripts/Data/DataLoader.cs:38)
DataLoader.Awake () (at Assets/Scripts/Data/DataLoader.cs:19)

Next, the code (the final line is Dataloader.cs:38)

ShipTypes shipTypes;
string path = Application.streamingAssetsPath + "/ShipTypes.json";
shipTypes = JsonUtility.FromJson<ShipTypes>(path);

Here are my classes

[System.Serializable]
public class ShipTypes
{
    public List<Ship> ships;
}

[System.Serializable]
public class Ship
{
    public string name;
    public int attack;
    public int defense;
    public int speed;
    public int range;
}

And finally here is my JSON

{
  "ships" : 
    [
        {
            "name": "Corvette",
            "attack" : 2,
            "defense" : 7,
            "speed" : 20,
            "range" : 8
        },
        {
            "name": "Frigate",
            "attack" : 4,
            "defense" : 6,
            "speed" : 10,
            "range" : 8
        },
        {
            "name": "Destroyer",
            "attack" : 8,
            "defense" : 8,
            "speed" : 10,
            "range" : 8
        },
        {
            "name": "Dreadnought",
            "attack" : 14,
            "defense" : 10,
            "speed" : 7,
            "range" : 8
        },
        {
            "name": "Battleship",
            "attack" : 20,
            "defense" : 12,
            "speed" : 5,
            "range" : 8
        }
    ]
}

Thank you very much.

Programmer
  • 121,791
  • 22
  • 236
  • 328
small502
  • 43
  • 1
  • 5

2 Answers2

3

The fix is to load the contents, the call requires JSON text, not a file path:

ShipTypes shipTypes;
string path = Application.streamingAssetsPath + "/ShipTypes.json";
string contents = File.ReadAllText(path);
shipTypes = JsonUtility.FromJson<ShipTypes>(contents);
Ron Beyer
  • 11,003
  • 1
  • 19
  • 37
1

You are supposed to supply the JSON contents not the path to the JSON file for the following method→

JsonUtility.FromJson<T>(json_content_in_string);

So it is advised that you read the contents first by

string path_to_json  = Application.streamingAssetsPath + "/ShipTypes.json";
string json_contents = File.ReadAllText(path_to_json);

Then convert

shipTypes = JsonUtility.FromJson<ShipTypes>(json_contents);
Hasan Emrah Süngü
  • 3,488
  • 1
  • 15
  • 33