Unity Android端对JSON数据的读取和修改

1.路径读取的几种方式

这里简单总结一下我们在开发安卓端时,常用的路径读取的几种方式:

  • Resources.Load<T>()
    • Resources文件夹是特殊文件夹,打包出APK或者生成EXE文件后,就不会存在这个外部路径了,它是内部动态加载资源。它是只读的,不能动态的修改。打包使会被压缩加密。
  • Application.streamingAssetsPath
    • StreamingAsset文件夹的内容会原封不动的打入包中,在Android端下是只读的,但是在PC端是可以读写的,必须放在根目录下,否则不能被读取到。在安卓平台下该目录下的文件被压缩到一个单独的.jar文件,可通过WWW读取文件中的数据,安卓端不能用IO的方式读取数据,可以用WWW或者UnityWebRequest相关读取。
    • "jar:file://" + Application.dataPath + "!/assets/"(最后的/要注意不能漏去)
  • Application.persistentDataPath
    • 当应用程序发布到IOS或者Android端时,这个路径会指向一个公共路径(运行时被创建),当软件更新或者覆盖安装时,这里的数据不会被清除,这个路径是可读写的,值得注意的是在IOS上就是应用程序的沙盒,但是在Android可以是程序的沙盒,也可以是sdcard,并且在Android打包时,ProjectSetting页面有一个选项Write Access,可以设置它的路径是沙盒还是sdcard;利用可以读写的特性,在安卓平台下,往往会将一些StreamingAsset文件中的Json数据,在程序运行时将其复制到此文件夹下,在对数据进行读取或者修改,也并不是所有的情况都得复制到此文件下,也得视情况而定。(Tips:当需要复制到该文件夹下,先需要判断文件是否存在)

思路:因为StreamingAsste文件夹在安卓端时只读的,但是Application.persistentDataPath文件夹是可以读写的,我们可以将JSON数据创建一份保存在Application.persistentDataPath目录下,供我们的读取和修改。


2.代码示例 安卓端读取和修改JSON数据(基本JSON读取介绍

JSON数据

{
    
    
    "StudentData":[
        {
    
    
            "ID":"001",
            "Name":"小明",
            "Age":"12"
        },
        {
    
    
            "ID":"002",
            "Name":"小花",
            "Age":"13"
        }
    ]
}

从StreamingAsset文件夹复制到persistentDataPath文件夹中

 //从StreamingAsset文件夹复制到persistentDataPath文件夹中
    IEnumerator CopyStreamingAssetData(string fileName)
    {
    
    
        string fromPath = "";

        if (Application.platform == RuntimePlatform.Android)
            fromPath = "jar:file://" + Application.dataPath + "!/assets/" + fileName;
        else
            fromPath = Application.streamingAssetsPath + "/" + fileName;

        string toPath = "jar:file://" + Application.persistentDataPath + "/" + fileName;

        UnityWebRequest request = UnityWebRequest.Get(fromPath);
        yield return request.SendWebRequest();

        if (!File.Exists(Application.persistentDataPath + "/" + fileName))
        {
    
    
            FileStream fs = File.Create(Application.persistentDataPath + "/" + fileName);
            fs.Close();
        }

        File.WriteAllBytes(Application.persistentDataPath + "/" + fileName, request.downloadHandler.data);
    }

从persistentData文件夹中读取数据

    
    IEnumerator ReadJson_IE(string path)
    {
    
    
        UnityWebRequest request = UnityWebRequest.Get("jar:file://" + Application.persistentDataPath + "/" + path);
        yield return request.SendWebRequest();
        data = JsonUtility.FromJson<Data>(request.downloadHandler.text);
        txt.text = request.downloadHandler.text+"\n当前的数量为:"+data.StudentData.Count;
    }

对应的JSON解析类

[Serializable]
public class Data {
    
    

    public List<Student> StudentData;
}
[Serializable]
public class Student {
    
    

    public string ID;
    public string Name;
    public string Age;
}

猜你喜欢

转载自blog.csdn.net/weixin_44446603/article/details/121367200
今日推荐