How to use Json to serialize and save data in Unity

In our last tutorial we saw how to serialize data and save it to file using binary formatter. In this tutorial, we will see how to do the same using Json utility.

The main advantage of using Json is you can serialize more data types. For example, a Vector 3 in Unity needs to be saved as an array of floats when using binary formatter but you can serialize a vector3 when using Json.

Refer to our previous tutorial to see how to make the data serializable

In this tutorial, we will see how to convert the data into Json and save it to file. We will also see how to retrieve it.

Json data flow

Json save data

Json utility is a part of Unity engine so there is no need to add any namespace. You need to add System.IO to be able to write and read files.

Save the converted data in a string and then write the string to a file

Here is the sample script

using System.IO;
using UnityEngine;

public class Save_script
{
    save_data sav=new save_data();//your serializable class that contains data

    string file_path=Application.persistentDataPath + "/gamedata.mine";

  
    void save_game()
    {
        string json_data=JsonUtility.ToJson(sav);
        File.WriteAllText(file_path,json_data);
        
    }
}

Load Json data

To load the Json data, you can read the content of the file to a string and then use the Json utility to convert the string to your class type.

Here is the sample script

using System.IO;
using UnityEngine;

public class load_script
{
    
    string file_path=Application.persistentDataPath + "/gamedata.mine";

  
    save_data load_data()
    {
             
        if(File.Exists(file_path))
        {
            string loaded_data=File.ReadAllText(file_path);
            save_data lod=JsonUtility.FromJson<save_data>(loaded_data);
            Debug.Log("lod.player_health");//just to just if the data is correct
            return lod;
        }
        else
        {
            Debug.Log("File doesn't exist");
            return null;
        }

        
    }
}

That’s it for the tutorial. If you have any other questions then you can leave it in the comment box below.

2 thoughts on “How to use Json to serialize and save data in Unity”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from VionixStudio

Subscribe now to keep reading and get access to the full archive.

Continue reading