Save data with JSON error

Hi! I’m trying save scriptable object inventory with JSON utility and sometimes give me error at the start.
I think the problem is in the “load” function but im not sure…
For the moment it is working with Iformater, but i prefer use JSON.
What am i doing wrong? A part of the error, the component is completely reset after start. For example, there is another scriptable object related in the editor (my item database), and this is removed after error.

I let save and load functions with IFormater and JSON utility. (JSON it is comment because does not work)

[ContextMenu("Save")]
    public void Save()
    {

        IFormatter formatter = new BinaryFormatter();
        Stream stream = new FileStream(string.Concat(Application.persistentDataPath, savePath), FileMode.Create, FileAccess.Write);
        formatter.Serialize(stream, Container);
        stream.Close();

        //string saveData = JsonUtility.ToJson(this, true);
        //BinaryFormatter bf = new BinaryFormatter();
        //FileStream file = File.Create(string.Concat(Application.persistentDataPath, savePath));
        //bf.Serialize(file, saveData);
        //file.Close();
    }

    [ContextMenu("Load")]
    public void Load()
    {
        if (File.Exists(string.Concat(Application.persistentDataPath, savePath)))
        {
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(string.Concat(Application.persistentDataPath, savePath), FileMode.Open, FileAccess.Read);
            Inventory newContainer = (Inventory)formatter.Deserialize(stream);
            for (int i = 0; i < Container.Items.Length; i++)
            {
                Container.Items[i].UpdateSlot(newContainer.Items[i].item, newContainer.Items[i].amount);
            }
            stream.Close();

            //BinaryFormatter bf = new BinaryFormatter();
            //FileStream file = File.Open(string.Concat(Application.persistentDataPath, savePath), FileMode.Open);
            //string data = bf.Deserialize(file).ToString();
            //JsonUtility.FromJsonOverwrite(data, this);
            //file.Close();

        }
        else
        {
            //Clear();
            Save();
        }
    }

Thank you in advance!

Problems with Unity “tiny lite” built-in JSON:

In general I highly suggest staying away from Unity’s JSON “tiny lite” package. It’s really not very capable at all and will silently fail on very common data structures, such as Dictionaries and Hashes and ALL properties.

Instead grab Newtonsoft JSON .NET off the asset store for free, or else install it from the Unity Package Manager (Window → Package Manager).

https://forum.unity.com/threads/jso…-not-working-as-expected.722783/#post-4824743

Also, always be sure to leverage sites like:

PS: for folks howling about how NewtonSoft JSON .NET will “add too much size” to your game, JSON .NET is like 307k in size, and it has the important advantage that it actually works the way you expect a JSON serializer to work in the year 2021.

Also, while we’re saving data, here are some Load/Save steps:

Don’t use the binary formatter/serializer: it is insecure, it cannot be made secure, and it makes debugging very difficult, plus it actually will NOT prevent people from modifying your save data on their computers.

When loading, you can never re-create a MonoBehaviour or ScriptableObject instance directly from JSON. The reason is they are hybrid C# and native engine objects, and when the JSON package calls new to make one, it cannot make the native engine portion of the object.

Instead you must first create the MonoBehaviour using AddComponent() on a GameObject instance, or use ScriptableObject.CreateInstance() to make your SO, then use the appropriate JSON “populate object” call to fill in its public fields.

If you want to use PlayerPrefs to save your game, it’s always better to use a JSON-based wrapper such as this one I forked from a fellow named Brett M Johnson on github:

Thanks @Kurt-Dekker , definitely im going to learn about how to use player prefs… looks the better option.
Thank you

1 Like

I wouldn’t say PlayerPrefs is a “better” option, but just another way to save small packets of data.

The JsonPlayerPrefs thing really helps to clean it up because instead of splattering all your data all over the Windows Registry (which is how PlayerPrefs does it), the above package writes it to a file on disk instead.