Error writing to a json file: JsonException: Can't add a value here,Error writing to a json file, JsonException: Can't add a value here

/*
Help! i’m new to unity and i’m trying to save my data in a json file
*/
using UnityEngine;
using UnityEngine.SceneManagement;
using LitJson;
using System.IO;

public class nextLevel : MonoBehaviour
{
public int levels = 0;
public float score = 0;
public string user = “”, pass = “”, hw = “Hello World”;
public int stars = 0, numJumps = 0, numCrash = 0, fell = 0, left = 0, right = 0, slow = 0;
JsonData stats;

public void LoadNextLevel()
{

    levels++;
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex+1);
    stats = JsonMapper.ToJson(save());
    File.WriteAllText(Application.dataPath + "/stats.json", stats.ToString());
}
public void Update()
{
    PlayerPrefs.SetInt("levels", levels);
}
public string save()
{
    try
    {
        user = PlayerPrefs.GetString("user");
        pass = PlayerPrefs.GetString("pass");
        score = PlayerPrefs.GetFloat("distance");
        stars = PlayerPrefs.GetInt("stars");
        numJumps = PlayerPrefs.GetInt("numJump");
        numCrash = PlayerPrefs.GetInt("numCrash");
        levels = PlayerPrefs.GetInt("levels");
        fell = PlayerPrefs.GetInt("fall");
        left = PlayerPrefs.GetInt("left");
        right = PlayerPrefs.GetInt("right");
        slow = PlayerPrefs.GetInt("slow");
        return user +","+ pass +","+ score.ToString() +","+ stars.ToString() +","+ 
        numJumps.ToString() +","+ numCrash.ToString() +","+ levels.ToString() +","+
        fell.ToString() + "," + left.ToString() + "," + right.ToString() + "," + slow.ToString();
    }
    catch
    {
        return hw;
    }

}

},/*
Help!! i’m new to unity and i’m trying to save my data in a json file
*/
using UnityEngine;
using UnityEngine.SceneManagement;
using LitJson;
using System.IO;

public class nextLevel : MonoBehaviour
{
public int levels = 0;
public float score = 0;
public string user = “”, pass = “”, hw = “Hello World”;
public int stars = 0, numJumps = 0, numCrash = 0, fell = 0, left = 0, right = 0, slow = 0;
JsonData stats;

public void LoadNextLevel()
{

    levels++;
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex+1);
    stats = JsonMapper.ToJson(save());
    File.WriteAllText(Application.dataPath + "/stats.json", stats.ToString());
}
public void Update()
{
    PlayerPrefs.SetInt("levels", levels);
}
public string save()
{
    try
    {
        user = PlayerPrefs.GetString("user");
        pass = PlayerPrefs.GetString("pass");
        score = PlayerPrefs.GetFloat("distance");
        stars = PlayerPrefs.GetInt("stars");
        numJumps = PlayerPrefs.GetInt("numJump");
        numCrash = PlayerPrefs.GetInt("numCrash");
        levels = PlayerPrefs.GetInt("levels");
        fell = PlayerPrefs.GetInt("fall");
        left = PlayerPrefs.GetInt("left");
        right = PlayerPrefs.GetInt("right");
        slow = PlayerPrefs.GetInt("slow");
        return user +","+ pass +","+ score.ToString() +","+ stars.ToString() +","+ 
        numJumps.ToString() +","+ numCrash.ToString() +","+ levels.ToString() +","+
        fell.ToString() + "," + left.ToString() + "," + right.ToString() + "," + slow.ToString();
    }
    catch
    {
        return hw;
    }

}

}

Just going to give a quick rundown of what JSON does and how you should use it for this problem. From your example it looks like you are using JSON entirely wrong.


The actual error you received is probably because you are not saving to a proper file path. Application.dataPath goes right to your assets folder so no need to add another / . ie. Application.dataPath + “myStats.json” rather than “Application.dataPath + “/myStats.json”. Only time you add the slash is if you are going down another directory, for example, Application.dataPath +”/Database/myStats.json" – where myStats.json is a file inside a folder called “Database” which is inside your overall asset folder.


For JSON, first thing you want to do is make a class for all of your saved variables. That would look like this. Keep in mind, you cannot save a float using JSON. Instead use the datatype “double” which is just another type of decimal variable with more spaces. You will have to convert them back and forth unfortunately, since unity uses floats for calculations. Add the prefix (float) any time you want to convert a double back into a float. Since a double is larger than a float, nothing is needed going the other way. It will just hack off the extra decimal places.

double myDouble = 10.234322212; 
float myFloat = (float)myDouble; 

Your class will thus look like this, using doubles instead of a floats.

   public class Stats
    {
        public string statsUser;
        public string statsPass;
        public double statDistance;
        public int statStars;
        public int statNumJump;
        public int statNumCrash;
        public int statLevels;
        public int statFell;
        public int statLeft;
        public int statRight;
        public int statSlow; 
    }

Once you have a class established, you can go ahead and start assigning the variables.

 Stats myStats = new Stats()
        {
            statsUser = PlayerPrefs.GetString("user"),
            statsPass = PlayerPrefs.GetString("pass"),
            statDistance = PlayerPrefs.GetFloat("distance")
        };

What the JSON mapper does is converts a C# class into a body of text that resembles code. That way any program can read the JSON formatted text and understand how to convert it back into C# code. This is how you “write” that class into a text file.

   JsonData jsonData = JsonMapper.ToJson(myStats);
   string jsonString = jsonData.ToString();
   File.WriteAllText(Application.dataPath + "stats.json", jsonString);

What that did is convert your stat class into a long string that looks something like this, then saved it as plain text.

  {
      "statsUser": "Bob",
      "statsPass": "3",
      "statDistance": "122.3221",
    }

I added the spacing above to show how it resembles code, but if you open up the text file it will look something like this with no spacing or indentation
__

{“statsUser”:“Bob”,“statsPass”: “3”, “statDistance”: “122.3221”}
__
You have now saved the JSON data. Whats great about JSON is you can convert that text document back into a C# class. For example,

     string jsonString = File.ReadAllText(Application.dataPath + "stats.json");
     myStats = JsonMapper.ToObject<Stats>(jsonString);

What that code does is read the text file, then convert it from text into the C# class that we created. It says that it is formatted as a class, so the Json Mapper can read it. And that’s how you use JSON. No need to jumble all your variables into a comma separated string. That would require you to write your own parser to read it again, and defeats the purpose of JSON.