[JsonUtility] cannot deserialize json to new instances of type X

Hi,
so i’m trying to create a “PlayerStats” object using the JsonUtility class. There are no errors in the Editor but whenever i run the code i get the Exception : System.ArgumentException: Cannot deserialize JSON to new instances of type ‘PlayerStats.’ and i don’t know why. I use the method just like they do in the documentation but i keep getting that exception. The json file was created using JU.ToJson and should work without problem. What am i missing ?

            if (File.Exists(savePath + "\\" + name + ".json")) {
                string saveData = File.ReadAllText(savePath + "\\" + name + ".json");
                GameObject localPlayer = (GameObject)Instantiate(Resources.Load("Player/" +                                                              JsonUtility.FromJson<PlayerStats>(saveData).race.ToString()));
            }

the json file :

{
    "race": 0,
    "playerName": "xxx",
    "initative": 10.0
}

PlayerStats.cs :

public class PlayerStats : MonoBehaviour {
    public Race race;
    public string playerName;

    public float initative = 10;
	// Use this for initialization
	void Start () {
	    
	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

In case anyone else comes across this and still wants to serialize MonoBehaviour or ScriptableObject, the fine print in the docs state the following:

However, when deserializing JSON into
subclasses of MonoBehaviour or
ScriptableObject, you must use
FromJsonOverwrite
; FromJson is not
supported and will throw an exception.

source: https://docs.unity3d.com/Manual/JSONSerialization.html

“PlayerStats” should not be a MonoBehaviour. The JsonUtility can only be used for data classes. MonoBehaviours are components which need to be attached to gameobjects. You can’t simply “create” an instance, that’s why it failed.

Try:

[System.Serializable]
public class PlayerStats
{
    public Race race;
    public string playerName;
    
    public float initative = 10;
}

Of course this class can not be attached to a gameobject. It’s only ment as a data class that represents your save data. Also note that the “Race” class also can’t be a MonoBehaviour. All classes you want to save / restore have to be normal serializable classes (or maybe derived from ScriptableObject, though i never used that JsonUtility myself).