I have a JSON file that is given as:
{
"Person": "true",
"Age": "true",
"Location": "false",
"Phone": "true"
}
I am able to read it in Unity by using the code below. I am using SimpleJSON library.
using System.Collections;
using System.Collections.Generic;
using System.IO;
using SimpleJSON;
using UnityEngine;
using UnityEngine.UI;
public class ReadWriteScene : MonoBehaviour {
public string jsonFile;
JSONNode itemsData;
string path;
// Start is called before the first frame update
void Start () {
path = Path.Combine (Application.streamingAssetsPath, "Settings.json");
if (File.Exists (path)) {
jsonFile = File.ReadAllText (path);
DeserializePages ();
}
}
void Update () {
}
public void DeserializePages () {
itemsData = JSON.Parse (jsonFile);
var parseJSON = JSON.Parse (jsonFile);
Debug.Log(parseJSON["Phone"].Value);
}
}
But I do not know how to write or make changes to the JSON via code? For example, how do I change the attribute "Age" to "false"?
CodePudding user response:
It's very easy.
itemsData["Age"] = "false";
Check https://docs.unity3d.com/Packages/[email protected]/api/SimpleJSON.JSONNode.html.
CodePudding user response:
itemsData["Age"] = "false";
File.WriteAllTextAsync(path, itemsData.ToString());
CodePudding user response:
It was quite easy. I used JSONObject and did the following:
public void SaveData(){
JSONObject json = new JSONObject();
json.Add("Person", "true");
json.Add("Age", "false");
json.Add("Location", "true");
json.Add("Phone", "true");
File.WriteAllText(path, json.ToString());
}
Know that, I did not create a new file, it replaces the already created file but make sure you add all the given attributes or else it will get erased.