Why can't I save a float in json?

I’m trying to save data into json ( Just learning the basics before I start implementing it into my game)

Here is my script:

using UnityEngine;
using System.Collections;
using System.IO;

[System.Serializable]
public class Data {

    public bool b;
    public double x;
    public int y;
    //public float z;
    public string text;
}

public class Saving : MonoBehaviour {

    public Data[] myData;

    void Update(){

        if (Input.GetKeyDown ("s")){ // Saves into json

            string saveText = LitJson.JsonMapper.ToJson (myData);

            File.WriteAllText (Application.dataPath + "/Save.txt", saveText);
        }

        if (Input.GetKeyDown ("a")){ // Loads json
    
            string loadedText = File.ReadAllText (Application.dataPath + "/Save.txt");

            LitJson.JsonData loadedData = LitJson.JsonMapper.ToObject (loadedText);

            print ( loadedText);
        }
    }
}

Now whats happening is that all variables save correctly ( yes even doubles ) except float, as soon as I remove the variable “z”, everything works fine.

Is this a error, or does json just not work with floats?? and if it does, what is the workaround?

It’s not anything to do with json, which is just a format. It’s the external library that you’re using to serialize to Json.
http://lmgtfy.com/?q=litjson+float

Ok so i’m using the LitJason plugin, so I should download another plugin or??

Edit: so at the end I discovered the best way was to just use unity default json: JsonUtility.ToJson

It also allows me to save/load vectors etc

1 Like