Unity 保存Json数据到本地文件(字典)
2017-06-07 13:31
453 查看
一、先导入Json 解析库;
下载地址:http://download.csdn.net/detail/u014076894/9606309二、开始代码的编写;
[csharp] viewplain copy
print?
//命名空间
using System.IO;
using System.Collections.Generic;
using LitJson;
[csharp] view
plain copy
print?
//相关变量声明:
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
print?
//初始化方法 如有需要,可重载初始化方法
public static void Init(string pFolderName, string pFileName) {
mFolderName = pFolderName;
mFileName = pFileName;
Dic_Value.Clear();
Read();
}
[csharp] view
plain copy
print?
//读取文件及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
print?
//将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
print?
//判断当前是否存在该key值
public static bool HasKey(string pKey) {
return Dic_Value.ContainsKey(pKey);
}
[csharp] view
plain copy
print?
//读取string值
public static string GetString(string pKey) {
if(HasKey(pKey)) {
return Dic_Value[pKey];
} else {
return string.Empty;
}
}
[csharp] view
plain copy
print?
//保存string值
public static void SetString(string pKey, string pValue) {
if(HasKey(pKey)) {
Dic_Value[pKey] = pValue;
} else {
Dic_Value.Add(pKey, pValue);
}
Save();
}
相关文章推荐
- Unity 保存Json数据到本地文件
- Unity 保存Json数据到本地文件
- Unity 中存储数据到JSON本地文件
- Unity IniFile 保存游戏数据到本地文件
- Unity 使用JSON实现本地数据保存和读取
- Unity 中保存数据到本地文件
- flex_将数据保存到本地文件;
- 解析数据文件之字符串转数组类型【里面是json格式化字典】类型
- 怎么直接让火狐输入json数据,而不是弹出文件保存对话框?
- 解决IE下返回json数据提示文件保存到问题
- BaseAdapter,这篇博客讲深入一些,实现从本地的JSON文件读取数据
- Unity 用C#脚本读取JSON文件数据
- 用C#编程从数据库中读取图片数据导进Excel文件的方法(如何从数据库中读取保存的文件,直接打开,中间不保存到本地)
- 【Unity3D插件】在Unity中读写文件数据:LitJSON快速教程 - 王选易
- (8)unity入门,玩家信息保存PlayerPrefs、IO、数据字典
- pyhton 从web获取json数据 保存到本地然后再读取
- 每次请求回的Json数据本地用sharedpreference保存
- [unity]保存服务器文件到本地并加载
- 关于使用java从http接口取数据保存到本地文件的中文乱码处理
- Unity 3d 保存玩家数据到本地之PlayerPrefs, C#封装