Unity 儲存Json資料到本地檔案
阿新 • • 發佈:2019-01-31
一、先匯入Json 解析庫;
二、開始程式碼的編寫;
//名稱空間
using System.IO;
using System.Collections.Generic;
using LitJson;
//相關變數宣告: private static string mFolderName; private static string mFileName; private static Dictionary<string, string> Dic_Value = new Dictionary<string, string>(); private static string FileName { get { return Path.Combine(FolderName, mFileName); } } private static string FolderName { get { return Path.Combine(Application.persistentDataPath, mFolderName); } }
//初始化方法 如有需要,可過載初始化方法
public static void Init(string pFolderName, string pFileName) {
mFolderName = pFolderName;
mFileName = pFileName;
Dic_Value.Clear();
Read();
}
//讀取檔案及json資料載入到Dictionary中 private static void Read() { if(!Directory.Exists(FolderName)) { Directory.CreateDirectory(FolderName); } if(File.Exists(FileName)) { FileStream fs = new FileStream(FileName, FileMode.Open); StreamReader sr = new StreamReader(fs); JsonData values = JsonMapper.ToObject(sr.ReadToEnd()); foreach(var key in values.Keys) { Dic_Value.Add(key, values[key].ToString()); } if(fs != null) { fs.Close(); } if(sr != null) { sr.Close(); } } }
//將Dictionary資料轉成json儲存到本地檔案 private static void Save() { string values = JsonMapper.ToJson(Dic_Value); Debug.Log(values); if(!Directory.Exists(FolderName)) { Directory.CreateDirectory(FolderName); } FileStream file = new FileStream(FileName, FileMode.Create); byte[] bts = System.Text.Encoding.UTF8.GetBytes(values); file.Write(bts,0,bts.Length); if(file != null) { file.Close(); } }
到此,簡單的儲存方法基本完成了。
三、舉例使用;
拿讀寫字串為例://判斷當前是否存在該key值
public static bool HasKey(string pKey) {
return Dic_Value.ContainsKey(pKey);
}
//讀取string值
public static string GetString(string pKey) {
if(HasKey(pKey)) {
return Dic_Value[pKey];
} else {
return string.Empty;
}
}
//儲存string值
public static void SetString(string pKey, string pValue) {
if(HasKey(pKey)) {
Dic_Value[pKey] = pValue;
} else {
Dic_Value.Add(pKey, pValue);
}
Save();
}
如有雷同,純屬巧合!
如有不足,歡迎指正!