Unity里用到的Json文件存取工具收集

一、序列化插件FullSerializer
下载链接Github–FullSerializer插件下载链接
1.1、利用FullSerializer插件,操作Json文件存取

//序列化之后存贮json文件
protected void SaveJsonFile(string path, T data) where T : class
    {
        fsData serializedData;
        var serializer = new fsSerializer();
        serializer.TrySerialize(data, out serializedData).AssertSuccessWithoutWarnings();
        var file = new StreamWriter(path);
        var json = fsJsonPrinter.PrettyJson(serializedData);
        file.WriteLine(json);
        file.Close();
    }
   public static T LoadJsonFile(string path) where T : class
    {
        if (!File.Exists(path)) return null;
        object deserialized = null;
        using (StreamReader file = new StreamReader(path))
        {
            string fileContents = file.ReadToEnd();
            fsData data = fsJsonParser.Parse(fileContents);
            fsSerializer fsSerializer = new fsSerializer();
            fsSerializer.TryDeserialize(data, typeof(T), ref deserialized).AssertSuccessWithoutWarnings();
            file.Close();
        }
        return deserialized as T;
    }

二、利用LitJson插件对Json文件进行操作读取
2.1、litjson插件简单读取json文件

public class TestClass
{
    public string myName;
    public int index;

}
 void Update()
    {
        if (Input.GetKeyDown(KeyCode.S))
        {
            TestClass cl = new TestClass();
            cl.myName = "测试";
            cl.index = 1;
            SaveJsonFile(Application.dataPath + "/Te/text.json", cl);
        }

        if (Input.GetKeyDown(KeyCode.R))
        {
            TestClass tecl = LoadJsonFile(Application.dataPath + "/Te/text1.json");
            Debug.Log("" + tecl.myName + "--" + tecl.index);
        }
    }

    public void SaveJsonFile(string path, T data) where T : class
    {
        if (!System.IO.File.Exists(path))
        {
            StreamWriter wr1 = new StreamWriter(path);
            wr1.Write("");
            Debug.Log("创建");
            wr1.Close();
        }
        string str = JsonMapper.ToJson(data);
        StreamWriter wr = new StreamWriter(path);
        wr.Write(str);
        Debug.Log("写入");
        wr.Close();
    }

    public T LoadJsonFile(string path) where T : class
    {
        if (!System.IO.File.Exists(path))
        {
            return null;
        }
        JsonReader jsonre = new JsonReader(File.ReadAllText(path));
        T tecl = JsonMapper.ToObject(jsonre);
        return tecl;

    }

你可能感兴趣的:(基础,json,unity,java)