當前位置:成語大全網 - 新華字典 - 如何從本地 讀取json文件 並用字典存儲起來

如何從本地 讀取json文件 並用字典存儲起來

Unity 保存Json數據到本地文件(字典)

壹、先導入Json 解析庫;

二、開始代碼的編寫;

[csharp] view plain copy

//命名空間

using System.IO;

using System.Collections.Generic;

using LitJson;

[csharp] view plain copy

//相關變量聲明:

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);

}

}

[csharp] view plain copy

//初始化方法 如有需要,可重載初始化方法

public static void Init(string pFolderName, string pFileName) {

mFolderName = pFolderName;

mFileName = pFileName;

Dic_Value.Clear();

Read();

}

[csharp] view plain copy

//讀取文件及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();

}

}

}

[csharp] view plain copy

//將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();

}

}

到此,簡單的保存方法基本完成了。

三、舉例使用;

拿讀寫字符串為例:

[csharp] view plain copy

//判斷當前是否存在該key值

public static bool HasKey(string pKey) {

return Dic_Value.ContainsKey(pKey);

}

[csharp] view plain copy

//讀取string值

public static string GetString(string pKey) {

if(HasKey(pKey)) {

return Dic_Value[pKey];

} else {

return string.Empty;

}

}

[csharp] view plain copy

//保存string值

public static void SetString(string pKey, string pValue) {

if(HasKey(pKey)) {

Dic_Value[pKey] = pValue;

} else {

Dic_Value.Add(pKey, pValue);

}

Save();

}