您当前的位置: 首页 >  unity

unity工具人

暂无认证

  • 3浏览

    0关注

    205博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

c# Json文件操作(用unity自带的JsonUtility来进行序列化)

unity工具人 发布时间:2021-03-31 23:02:19 ,浏览量:3

用unity自带的JsonUtility来进行序列化

一、检查路径中的Json文件是否存在,不存在则新建

  /// 
    /// // 判断是否已有相同文件,没有就新建
    /// 
    /// 
    /// 
    public bool CheckJsonPath(string path)
    {
        if (!File.Exists(path))  // 判断是否已有相同文件 
        {
           
            CreateJson(path);
            
            print("未找到文件,已创建新的文件:"+path);
            return false;
        }
        else
        {
            print("文件存在");
            return true;
        }
    }
    /// 
    /// 新建Json
    /// 
    /// 新建的位置
    /// 对象
    public static void CreateJson(string strPath)
    {
        InfoList infoList = new InfoList();
        //序列化
        string json = JsonUtility.ToJson(infoList);
        StreamWriter sw = new StreamWriter(strPath);
        sw.Write(json);
        sw.Close();
    }

上边代码中的数据类

[System.Serializable]
public class InfoList
{
    public List autoInfos = new List();
}
二、读取json文件中的文本并反序列化
    public string ReadJson(string FullPath)
    {
        //string FilePath = Application.streamingAssetsPath + "/JsonPerson.json";
        string JsonString = File.ReadAllText(FullPath);
        //反序列化
        JsonUtility.FromJson(JsonString);
        return JsonString;
    }

json文件,相对于xml和txt来讲更小,存取更快,更方便。 以上是使用unity自带的JsonUtility来进行序列化的示例。

我们也可以尝试使用其它的工具进行序列化和反序列化操作 例如: LitJson的使用 Json序列化工具 Newtonsoft.Json的使用

关注
打赏
1656671177
查看更多评论
立即登录/注册

微信扫码登录

0.0363s