当前位置:   article > 正文

Unity 读取Json常用的几种方式_unity 访问json

unity 访问json

使用的命名空间如下
using LitJson;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

注意:安卓路径
本地路径:“/storage/emulated/0/” + fileName;
安装后:Application.persistentDataPath

注意事项:

安卓端运行apk提示”UnauthorizedAccessException:Access to the path “/xx/xx.xx” is denied.“
解决方法 ①在AndroidManifest.xml中的application标签中添加:android:requestLegacyExternalStorage=“true”
    ②安装在安卓手机上apk软件,需要设置软件权限管理,将读写设备存储改成始终允许

1、通过UnityWebRequest获取本地StreamingAssets文件夹中的Json文件

      /// <summary>
    /// 通过UnityWebRequest获取本地StreamingAssets文件夹中的Json文件
    /// </summary>
    /// <param name="fileName">文件名称</param>
    /// <returns></returns>
    public string UnityWebRequestJsonString(string fileName)
    {
        string url;

        #region 分平台判断 StreamingAssets 路径
        //如果在编译器 或者 单机中  ……
#if UNITY_EDITOR || UNITY_STANDALONE

        url = "file://" + Application.dataPath + "/StreamingAssets/" + fileName;
        //否则如果在Iphone下……
#elif UNITY_IPHONE

            url = "file://" + Application.dataPath + "/Raw/"+ fileName;
            //否则如果在android下……
#elif UNITY_ANDROID
            url = "jar:file://" + Application.dataPath + "!/assets/"+ fileName;
#endif
        #endregion
        UnityWebRequest request = UnityWebRequest.Get(url);
        request.SendWebRequest();//读取数据
        while (true)
        {
            if (request.downloadHandler.isDone)//是否读取完数据
            {
                return request.downloadHandler.text;
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

2、通过UnityWebRequest和StreamReader读取本地StreamingAssets文件夹中的Json文件

 	/// <summary>
    /// 通过UnityWebRequest和StreamReader读取本地StreamingAssets文件夹中的Json文件
    /// </summary>
    /// <param name="jsonName">json文件名</param>
    /// <returns></returns>
    public string StreamReaderJsonFromSSPath(string jsonName)
    {
        string url;
        #region 分平台判断 StreamingAssets 路径
        //如果在编译器 或者 单机中  ……
#if UNITY_EDITOR || UNITY_STANDALONE
        url = Application.dataPath + "/StreamingAssets/" + jsonName;
        //否则如果在Iphone下……
#elif UNITY_IPHONE

            url = Application.dataPath + "/Raw/"+ fileName;
            //否则如果在android下……
#elif UNITY_ANDROID
            url =  Application.dataPath + "!/assets/"+ fileName;
#endif
        #endregion
        UnityWebRequest webRequest = UnityWebRequest.Get(url);
        webRequest.SendWebRequest();//读取数据
        while (true)
        {
            if (webRequest.isNetworkError)
            {
                Debug.LogError(url + "请求错误:" + webRequest.error);
            }
            else
            {
                if (webRequest.downloadHandler.isDone)//是否读取完数据
                {
                    //读取
                    Encoding endoning = Encoding.GetEncoding("utf-8");//识别Json数据内容中文字段
                    StreamReader streamReader = new StreamReader(url, endoning);
                    string str = streamReader.ReadToEnd();
                    streamReader.Close();
                    return str;
                }
            }
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

3、通过StreamReader读取本地StreamingAssets文件夹中的Json文件

   /// <summary>
    /// 通过StreamReader读取本地StreamingAssets文件夹中的Json文件
    /// <param name="jsonName">json文件名或文件名路径</param>
    /// </summary>
    public string ReadJsonFromStreamingAssetsPath(string jsonName)
    {
        string url = Application.streamingAssetsPath + "/" + jsonName;
        Encoding endoning = Encoding.UTF8;//识别Json数据内容中文字段
        StreamReader streamReader = new StreamReader(url, endoning);
        string jsonData = streamReader.ReadToEnd();
        //JsonData jsonData = JsonMapper.ToObject(str);  //如果需要返回JsonData类型数据内容需取消该行注释,并将函数string类型改成JsonData
        return jsonData;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

4、通过FileStream读取本地StreamingAssets文件夹中的文件

	/// <summary>
    /// 通过FileStream读取本地StreamingAssets文件夹中的文件
    /// </summary>
    /// <param name="jsonName"></param>
    /// <returns></returns>
    public string GetAllFileInfos(string jsonName)
    {
        string jsonPath = Application.streamingAssetsPath + "/" + jsonName;
        try
        {
            using (FileStream fs = new FileStream(jsonPath, FileMode.Open, FileAccess.Read))
            {
                fs.Seek(0, SeekOrigin.Begin);
                var bytes = new byte[fs.Length];
                fs.Read(bytes, 0, (int)fs.Length);
                string jsonData = Encoding.UTF8.GetString(bytes);
                fs.Flush();
                fs.Dispose();
                fs.Close();
                return jsonData;
            }
            //Debug.Log("所有文件资源信息Assets下文件夹数量:" + fileInfos.Count);
        }
        catch (Exception e)
        {
            Debug.LogError(e.Message);
            Debug.LogError("文件读取异常:" + jsonPath);
            return string.Empty;
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

5、通过File.ReadAllText 读取本地或外部配置文件


    /// <summary>
    /// 加载本地或外部的Json文件--
    /// </summary>
    /// <param name="path">Json文件路径</param>
    /// <returns></returns>
    public string ReadConfigFile(string path)
    {
        string filePath;

        if (Application.platform == RuntimePlatform.Android)
        {
            filePath = "/storage/emulated/0/" + path;
            Debug.Log("安卓本地文件" + filePath);
        }
        else
        {
            filePath = Application.streamingAssetsPath + "/" + path;
            Debug.Log("本地文件" + filePath);
        }

        if (File.Exists(filePath))
        {
            //读取
            string jsonData = File.ReadAllText(filePath, endoning);
            return jsonData;
        }
        else
        {
            Debug.LogError("文件不存在" + filePath);
            return null;
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/794191
推荐阅读
相关标签
  

闽ICP备14008679号