ユニティはJsonデータをローカルファイルに保存します。
2822 ワード
一、まずJson解析ライブラリを導入する。
ダウンロード先:http://download.csdn.net/detail/u014076894/9606309
二、コードの作成を開始する;
三、例を挙げて使う。
読み文字列を例にとる:
足りないところがあれば、ご指摘ください。
ダウンロード先:http://download.csdn.net/detail/u014076894/9606309
二、コードの作成を開始する;
//
using System.IO;
using System.Collections.Generic;
using LitJson;
// :
private static string mFolderName;
private static string mFileName;
private static Dictionary Dic_Value = new Dictionary();
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();
}
もし同じことがあったら全く偶然です。足りないところがあれば、ご指摘ください。