How can I format a proper json string to a text file and add a empty line between each string ?

  • Thread starter Thread starter chocolade
  • Start date Start date
C

chocolade

Guest
This is how I'm using the json :

Using ToJson

public void Save()
{
SaveObject saveObject = new SaveObject();
for (int i = 0; i < objectsToSave.Count; i++)
{
var x = objectsToSave.GetComponents<Component>();
var y = x.Where(component => component is IStateQuery).ToList();
List<KeyToValue> myObjects = new List<KeyToValue>();
foreach(var z in y)
{
var w = z as IStateQuery;
myObjects.Add(new KeyToValue(w.UniqueId.ToString(), w.GetState()));

}
saveObject.position = objectsToSave.position;
saveObject.scaling = objectsToSave.localScale;
saveObject.rotation = objectsToSave.rotation;

saveObject.objects = myObjects;


string json = JsonUtility.ToJson(saveObject);

SaveSystem.Save(json);
}
}



Then saving the string to a text file :

public static void Save(string saveString)
{
File.AppendAllText(SAVE_FOLDER + "/" + "savegame.txt", saveString + Environment.NewLine + Environment.NewLine);
}

But I have some problems with the AppendAllText

If I'm using only once with the Environment.NewLine it will not add a line between the saveString's so the text saved file content will be like this :


{"objects":[{"Key":"367f6ac2-6fd3-4c99-91e5-cc335a104ac4","Value":"{\"s1\":false}"}],"instanceID":0,"position":{"x":8.140000343322754,"y":0.0,"z":0.0},"scaling":{"x":1.0,"y":1.0,"z":1.0},"rotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0}}
{"objects":[{"Key":"ecb45f8e-463c-4fe3-a436-5d836165bcce","Value":"{\"s1\":false}"}],"instanceID":0,"position":{"x":-11.229999542236329,"y":0.0,"z":8.920000076293946},"scaling":{"x":1.0,"y":1.0,"z":1.0},"rotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0}}

And if I'm using the Environment.NewLine twice then the format in the text file will be with a empty line between the strings but it also will add empty line at the bottom and I don't want it to add empty line at the bottom.

{"objects":[{"Key":"367f6ac2-6fd3-4c99-91e5-cc335a104ac4","Value":"{\"s1\":false}"}],"instanceID":0,"position":{"x":8.140000343322754,"y":0.0,"z":0.0},"scaling":{"x":1.0,"y":1.0,"z":1.0},"rotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0}}

{"objects":[{"Key":"ecb45f8e-463c-4fe3-a436-5d836165bcce","Value":"{\"s1\":false}"}],"instanceID":0,"position":{"x":-11.229999542236329,"y":0.0,"z":8.920000076293946},"scaling":{"x":1.0,"y":1.0,"z":1.0},"rotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0}}


The second problem is how to format the content in the text file to be in a proper json format ?

Instead


{}
{}



It should be something like :

[
{},
{}
]





danieli

Continue reading...
 
Back
Top