Unity 保存Json数据到本地文件
来源:互联网 发布:淘宝的欧莱雅是真的吗 编辑:程序博客网 时间:2024/05/22 13:10
一、先导入Json 解析库;
下载地址: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<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();
- }
-
- 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();
- }
- }
- }
-
- 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();
- }
- }
到此,简单的保存方法基本完成了。三、举例使用;
拿读写字符串为例:-
- public static bool HasKey(string pKey) {
- return Dic_Value.ContainsKey(pKey);
- }
-
- public static string GetString(string pKey) {
- if(HasKey(pKey)) {
- return Dic_Value[pKey];
- } else {
- return string.Empty;
- }
- }
-
- public static void SetString(string pKey, string pValue) {
- if(HasKey(pKey)) {
- Dic_Value[pKey] = pValue;
- } else {
- Dic_Value.Add(pKey, pValue);
- }
- Save();
- }
0 0