Unity 安卓将数据保存为json并读取

1.使用LitJson解析数据,保存数据为json

csharp 复制代码
// 创建一个字典用来给读取json后赋值
 public Dictionary<string, List<string>> myDictionary = new Dictionary<string, List<string>>();
 
public void LoadDeviceDic()
    {

        string filePath = Path.Combine(Application.persistentDataPath, "dData.json");

        // 检查文件是否存在
        if (File.Exists(filePath))
        {
            // 从文件中读取 JSON 数据
            string json = File.ReadAllText(filePath);

            // 将 JSON 数据转换为字典
            myDictionary = JsonMapper.ToObject<Dictionary<string, List<string>>>(json);


            Debug.Log("Dictionary data loaded from: " + filePath);
         DeviceManager.GetInstance().myDictionary = myDictionary;
            // 示例:输出加载的数据
            foreach (var pair in myDictionary)
            {
                Debug.Log("Key: " + pair.Key + ", Value: " + pair.Value + ", " + pair.Value);
            }
        }
        else
        {
            Debug.LogError("Dictionary data file not found!");
        }
       
    }

保存数据为json

csharp 复制代码
public static void SaveDiviceDicdate(Dictionary<string, List<string>> pairs)
    {
        JsonData jsonData = JsonMapper.ToJson(pairs);
       
        // 获取文件路径
        string filePath = Path.Combine(Application.persistentDataPath, "dData.json");
        Debug.LogWarning(jsonData.ToString());
        // 保存 JSON 字符串到文件
        // File.WriteAllText(filePath, jsonData.ToString(), Encoding.UTF8);
        File.WriteAllText(filePath, jsonData.ToString(), Encoding.UTF8);
        Debug.Log("Dictionary data saved to: " + filePath);
    }
相关推荐
Lyyaoo.5 分钟前
【MySQL】SQL优化
android·sql·mysql
ImTryCatchException12 分钟前
Android 性能优化实战手册:从理论到落地的完整方法论
android·性能优化
sun00770022 分钟前
qnx网络相关模块,全链路,硬件网卡 → 用户态驱动 (.so) → io‑pkt/io‑sock(用户态 TCP/IP + 转发 + 控制)
android
赏金术士1 小时前
Android app 项目:模块打包 AAR 教程
android·热修复·tinker·aar打包
ImTryCatchException1 小时前
React Native 嵌入现有 Android 项目:踩坑记录与解决方案
android·react native·react.js
曼岛_1 小时前
[安卓逆向]在Android Studio中编写SO文件并测试调用 (四)
android·ide·android studio
ellis19702 小时前
Unity中使用Cursor辅助开发
unity
ImTryCatchException2 小时前
Android 卡顿诊断 SDK:从痛点出发的设计思考
android·gitee
流星白龙2 小时前
【MySQL高阶】14.MySQL存储结构
android·数据库·mysql
流星白龙2 小时前
【MySQL高阶】15.MySQL存储结构,页结构
android·mysql·adb