Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by lonches014029 · Oct 22, 2019 at 08:43 PM · jsonsave data

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;
     }

 }

}

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Strixie13 · Oct 23, 2019 at 01:47 PM

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

114 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Saves on android, could not find file 0 Answers

Fail to load data from json to list of list. 1 Answer

JsonUtility.ToJson returns empty file 2 Answers

Unity google save cloud service: How to build a good save system? 0 Answers

JSON not saving game object list 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges