Json文件的操作

【JSON文件】

1、保存文件(序列化),将程序对象保存到本地

//程序对象类
 public class Paths
    {
        public string Name;
        public List position;
        public List rotation;
    }

    Paths paths;
    /// 
    /// 初始化路径类
    /// 
    void InitPaths()
    {
        paths = new Paths();
        paths.Name = "这是一个测试";
        paths.position = InputData.listPosition;
        paths.rotation = InputData.listRotation;
    }

    /// 
    /// 保存json
    /// 
    /// 
    //private void SaveJson(string pathName)
    private void SaveJson()
    {
        //string savePath = @"C:\Users\T01015\Desktop\Test01.json";
        //string savePath = @"D:\AutoPath";
        if (!Directory.Exists(savePath))
        {
            //文件夹不存在时自动创建文件夹
            Directory.CreateDirectory(savePath);
        }

        InitPaths();
        DirectoryInfo dir = new DirectoryInfo(savePath);

        string json = JsonUtility.ToJson(paths);
        File.WriteAllText(savePath + @"\" + "方案" + dir.GetFiles().Length + ".json", json, Encoding.UTF8);

        print("保存的地址:" + savePath);
    }

2、读取文件(反序列化),将文件转换为对象供程序使用

 void LoadJson(string txtName)
    {
        //清除场景路线图
        for (int i = 0; i < pointPoll.childCount; i++)
        {
            Destroy(pointPoll.GetChild(i).gameObject);
        }

        string str = File.ReadAllText(savePath + @"\" + txtName + ".json" , Encoding.Default);
        paths = JsonUtility.FromJson(str);//解析json

        print(paths.Name);
        foreach (Vector3 item in paths.position)
        {
            print(item.x+","+item.y+","+item.z);
        }
    }

坑点:如有创建集合对象类,那么该对象类要标记[Serializable],否则解析不到内容。例如:

// Json解析为该对象
public class Response
{
    public List list;
}

[Serializable]
public class Student
{
    public int id;
    public string name;
}

 

你可能感兴趣的:(C#技术记录)