Saving list element information in json

Hello everyone. I have a code like below. Basically it saves and loads data from json. But I also need to save the information of the elements in the listItem list. How can I solve this? The elements of the lists are saved and loaded correctly. I also need to save the information of the elements of the listItem list.

using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using System.Security.Cryptography;
using System.Text;
public class HandlerListSave : MonoBehaviour
{
    public static HandlerListSave instance;
    public List<BoxData> listBox;
    public List<ShelfData> listShelf;
    public List<ItemSO> listItem;

    void Awake()
    {
        instance = this;
    }
    void Start()
    {
        LoadData(Application.persistentDataPath + "/combinedData.json");
    }
    void OnApplicationQuit()
    {
        SaveData(Application.persistentDataPath + "/combinedData.json");
    }

    void SaveData(string filePath)
    {
        bool fileExists = File.Exists(filePath);

        CombinedData combinedData = new() { listBoxData = listBox, listShelfData = listShelf, listItemData = listItem };
        string jsonData = JsonUtility.ToJson(combinedData, true);

        if (fileExists)
        {
            Debug.Log("The data was written to the already existing " + filePath + " path.");
        }
        else
        {
            Debug.Log("There are no save file in this " + filePath + " path. The data was written to a new save file.");
        }

        File.WriteAllText(filePath, jsonData );
    }
 
    void LoadData(string key, string filePath)
    {
        if (File.Exists(filePath))
        {
            string encryptedData = File.ReadAllText(filePath);
            CombinedData data = JsonUtility.FromJson<CombinedData>(encryptedData );

            listBox = data.listBoxData;
            listShelf = data.listShelfData;
            listItem = data.listItemData;
            Debug.Log("Data was successfully loaded from path " + filePath + " with key: " + key + ".");
        }
        else
        {
            Debug.Log("No save found in path " + filePath + ". Lists cleared and prepared.");
            ClearLists();
        }
    }
    void ClearLists()
    {
        listBox = new List<BoxData>();
        listShelf = new List<ShelfData>();
        listItem = new List<ItemSO>();
    }
}

You would need ItemSO to be a serializable class or struct. From its name I assume it’s actually a ScriptableObject type. So what you need is either:

  • Not to use a ScriptableObject here, and instead use a serializable class or struct
  • To save a list of some kind of identifier you can use to load the ScriptableObject asset. This could be a name for Resources.Load, or an asset address for the Addressables package, or some kind of custom identifier that you use internally to look up these objects.
2 Likes