Unity 保存Json数据到本地文件(字典)

发表于2017-12-21
评论0 6.1k浏览


在做本地存储的时需要写入到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<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();  
    }  
//读取文件及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();  
    } 

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引