- Home /
Inserting JSON and saving new values
PROJECT STATUS:
I was able to create an initial json object, insert values into it and save it.
Now I want to add a new entry to it and save that, and so on, and so on. WriteAllText will overwrite the current file. I've tried AppendAll, which kinda works, but I'd had some odd results. One field would save old data even after the variable values were changed.
public string GroupName="6th Batalion";
public string GroupMemberID="TG";
public string GroupMemberName="Tommy Gun";
public string GroupEquipmentID="TG1";
public string GroupEquipmentDescription="AR-9 machine gun";
void Start ()
{
Testjson();
}
public void Testjson()
{
var groupdata = new JSONObject
{
{"GroupID", GroupID},
{"GroupMemberName" , GroupMemberName},
};
var equipmentdata = new JSONObject
{
{"EquipmentID" , GroupEquipmentID},
{"EquipmentDescription" , GroupEquipmentDescription},
};
var maindata = new JSONObject
{
{"Group Name" , GroupName},
{"Group Member" , groupdata},
{"Group Equipment" , equipmentdata}
};
//return maindata;
Debug.Log(maindata);
File.WriteAllText(Application.dataPath + "/bandtest.json", maindata.ToString());
}
Results: {"Group Name":"6th Batalion","Group Member":{"GroupMemberID":"TG","GroupMemberName":"Tommy Gun"},"Group Equipment":{"EquipmentID":"TG1","EquipmentDescription":"AR-9 machine gun"}} Works great here! Now we change the variables public string GroupName="6th Batalion"; public string GroupMemberID="STF"; public string GroupMemberName="SpikeHawk ThunderFist"; public string GroupEquipmentID="STF1"; public string GroupEquipmentDescription="Vulcan Cannon";
What's the best way to save the new data and keep the old data? Do I make two separate json files and create a third with all of them? Thanks!
Answer by QuiZr · Jul 17, 2016 at 03:07 PM
Parse old data, make changes, serialize, save.
Also, You shouldn't combine path like this (#48):
File.WriteAllText(Application.dataPath + "/bandtest.json", maindata.ToString());
But instead use System.IO.Path.Combine(). Also, Application.persistentDataPath is the "right place" to save data.
var path = System.IO.Path.Combine(Application.persistentDataPath, "bandtest.json");
File.WriteAllText(path, maindata.ToString());
Just overwrite it every time. Remember to put File.WriteAllText()
in try-catch block for catching all exceptions that can occur (out of space, file already in use, file system stuff etc.).
I don't fully understand the answer from above, but just wanted to check if it worked? Did you manage not to lose your previous data and add new atop of it?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Position Translation problem 1 Answer
Unity Saved Serialized Levels 0 Answers
How to save and load any data type? 1 Answer