Unity 保存Json数据到本地文件

一、先导入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 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();
    }

如有雷同,纯属巧合!
如有不足,欢迎指正!

你可能感兴趣的:(Unity3D随笔)