Unity 生成/解析 Json, Json陣列 儲存到本地
阿新 • • 發佈:2020-09-18
StringBuilder sb = new StringBuilder();
JsonWriter writer = new JsonWriter(sb);
writer.WriteArrayStart();
writer.WriteObjectStart();
writer.WritePropertyName("ObjName");
writer.Write(key);
writer.WritePropertyName("ClassName");
writer.Write(str_className);
writer.WriteObjectEnd();
writer.WriteArrayEnd();
這是已經生成了 sb.tostring();
解析 生成的json
string json = sb.tostring(); JsonData data = new JsonData(); data = JsonMapper.ToObject(json); foreach (JsonData item in data) { string objname = (string)item["ObjName"]; // GameObject obj = GameObject.Find(objname); string classname = (string)item["ClassName"]; string[] _classname = classname.Split('|'); List<string> list_className = new List<string>(); for (int i = 0; i < _classname.Length; i++) { list_className.Add(_classname[i]); } dic.Add(objname, list_className); }
將json 儲存到本地
private void Save(string jsong) { //string values = JsonMapper.ToJson(dic); string values = jsong; Debug.Log(values); //找到當前路徑 FileInfo file = new FileInfo(filePath+ "/Dependence.bytes"); //判斷有沒有檔案,有則開啟檔案,,沒有建立後開啟檔案 StreamWriter sw = file.CreateText(); //ToJson介面將你的列表類傳進去,,並自動轉換為string型別 // string json = JsonMapper.ToJson(personList.dictionary); //將轉換好的字串存進檔案, sw.WriteLine(values); //注意釋放資源 sw.Close(); sw.Dispose(); }