Unity JSON将数据添加到现有json数据 [英] Unity JSON Add data to existing json data
问题描述
我正在为多个数据库设置创建索引.每次创建新的数据库时,我都需要一个索引,以便该人员可以连接到他们要处理的数据库.将索引保存在json文件中后,一旦再次加载它,如何在不删除现有数据的情况下添加到索引上?我看过的大多数教程都告诉您如何保存和加载,但不能告诉您如何使用现有数据.谢谢!由于这是一个非常简单的操作,因此我正在使用JSONUtility,但我不反对其他库的任何建议.
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.
推荐答案
通过将Json保存为List
,您可以真正简化此操作.当您要修改现有的时,只需加载它并继续使用Add
函数添加到列表中即可.仅在确实需要时保存它.
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的JSONUtility
无法序列化/反序列化数组或列表,因此我们需要使用在JSONUtility
之上构建的JsonHelper
包装器.您可以在此处获得.
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;
}
创建列表及其:
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(必须作为数组加载,然后转换回List):
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.
这篇关于Unity JSON将数据添加到现有json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!