Reputation: 305
I'm creating an index for a multiple database setup. each time a new db is created, I need an index so the person can connect to the database they want to work on. After the index is saved in a json file, once I load it up again, how do I add on to it without erasing the existing data? Most tutorials I've looked at tell you how to save and load but not what you can do with existing data. Thanks! While I'm using JSONUtility because this is a very simple operation, I'm not opposed to any recommendations for other libraries.
Upvotes: 1
Views: 10121
Reputation: 125325
You can really simplify this by saving the Json as a List
. When you want to modify the existing one, just load it and keep adding to the List with the Add
function. Only save it when you really have to.
Unity's JSONUtility
cannot serialize/de-serialize array or List so we need to use the JsonHelper
wrapper that is built on top of JSONUtility
. You can get that here.
Test data to load serialize and de-serialize:
[Serializable]
public class PlayerData
{
public string name;
public int score;
}
Create list of it and to it:
List<PlayerData> saveListData = new List<PlayerData>();
PlayerData saveData = new PlayerData();
saveData.name = "Programmer";
saveData.score = 80;
saveListData.Add(saveData);
Save(Must be converted to array to save it):
string jsonToSave = JsonHelper.ToJson(saveListData.ToArray());
PlayerPrefs.SetString("Data", jsonToSave);
PlayerPrefs.Save();
Load(Must be loaded as array then converted back to List):
string jsonToLoad = PlayerPrefs.GetString("Data");
//Load as Array
PlayerData[] _tempLoadListData = JsonHelper.FromJson<PlayerData>(jsonToLoad);
//Convert to List
List<PlayerData> loadListData = _tempLoadListData.OfType<PlayerData>().ToList();
for (int i = 0; i < loadListData.Count; i++)
{
Debug.Log("Got: " + loadListData[i].name);
}
Add more stuff to the loaded data?
loadListData.Add(new PlayerData());
loadListData.Add(new PlayerData());
loadListData.Add(new PlayerData());
loadListData.Add(new PlayerData());
You can then save it again.
Upvotes: 2
Reputation: 11
Read in the existing JSON if it exists, keep it in a string. Then when you are ready to save, you just need to concat the old JSON to the newly generated JSON and save to disk.
Hint: use Json.NET if you are not already.
Upvotes: 0