Unity Json檔案的讀取與寫入
阿新 • • 發佈:2020-12-29
主要是用Json檔案儲存場景內物體的位置名稱等資訊,並且用的時候需要讀取。
1、建立需要儲存的類
public class EachModel { public string ModelName; public string FileSize; public string FileName; public string PicName; public string[] Pos; public string[] Roate; public string[] Scale; public EachModel() { Pos = new string[3]; Roate = new string[4]; Scale = new string[3]; } public EachModel(string ModelName, string FileName, string PicName, string[] Pos, string[] Roate, string[] Scale) { this.ModelName = ModelName; this.FileName = FileName; this.PicName = PicName; for (int i = 0; i < Pos.Length; i++) { this.Pos[i] = Pos[i]; this.Roate[i] = Roate[i]; this.Scale[i] = Scale[i]; } this.Roate[3] = Roate[3]; } }
以及類的集合
public class ModelList { public List<EachModel> sites = new List<EachModel>(); }
將site內容轉化成Json檔案寫入
private void SaveModels(Transform model) { print(configPath); //string filePath = Application.streamingAssetsPath + @"/Config/JsonModel.json"; ModelList r = newModelList(); EachModel myModel = new EachModel(); myModel.Pos = new string[] { model.position.x.ToString("f2"), model.position.y.ToString("f2"), model.position.z.ToString("f2") }; myModel.Roate = new string[] { model.rotation.x.ToString("f2"), model.rotation.y.ToString("f2"), model.rotation.z.ToString("f2"), model.rotation.w.ToString("f2") }; myModel.Scale = new string[] { model.localScale.x.ToString("f2"), model.localScale.y.ToString("f2"), model.localScale.z.ToString("f2") }; //判斷config檔案是否存在,如果存在就讀取Json裡的內容來更新site if (File.Exists(configPath)) { StreamReader streamreader = new StreamReader(Application.streamingAssetsPath + "/Config/JsonModel.json");//讀取資料,轉換成資料流 JsonReader js = new JsonReader(streamreader);//再轉換成json資料 r = JsonMapper.ToObject<ModelList>(js);//讀取 if (IsAdd) { r.sites.Add(myModel); } else { for (int i = 0; i < r.sites.Count; i++) { if (r.sites[i].FileName.Equals(fileName.text)) { r.sites[i] = myModel; break; } } } streamreader.Close(); streamreader.Dispose(); } else { r.sites.Add(myModel); } //找到當前路徑 FileInfo file = new FileInfo(configPath); //判斷有沒有檔案,有則開啟檔案,,沒有建立後開啟檔案 StreamWriter sw = file.CreateText(); //ToJson介面將你的列表類傳進去,,並自動轉換為string型別 string json = JsonMapper.ToJson(r);
//避免中文字元亂碼 Regex reg = new Regex(@"(?i)\\[uU]([0-9a-f]{4})"); json = reg.Replace(json, delegate (Match m) { return ((char)System.Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); }); //將轉換好的字串存進檔案, sw.WriteLine(json); //注意釋放資源 sw.Close(); sw.Dispose(); }
寫入Json的時候已經有讀取Json的操作了,如果只是讀取:
private ModelList modelDatalList = new ModelList(); private void UpdateData() { string path = Application.streamingAssetsPath + "/Config/JsonModel.json"; if (!File.Exists(path)) { return; } StreamReader streamreader = new StreamReader(Application.streamingAssetsPath + "/Config/JsonModel.json");//讀取資料,轉換成資料流 JsonReader js = new JsonReader(streamreader);//再轉換成json資料 modelDatalList = JsonMapper.ToObject<ModelList>(js);//讀取 streamreader.Close(); streamreader.Dispose(); }
把Json內容轉化成ModelList類,輸出modelDatalList.sites即可