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);
    }
相关推荐
五阿哥永琪6 小时前
MySQL中操作json的函数!
数据库·mysql·json
fengci.10 小时前
Microweber CMS 未授权路径穿越漏洞(CVE-2026-65694)
android·开发语言·前端·学习·php
stevenzqzq11 小时前
Android 矢量图(Vector Drawable)核心坐标与尺寸机制技术文档
android
plainGeekDev11 小时前
运行时获取依赖 → 编译时注入
android·java·kotlin
Wiktok12 小时前
Vue3(Vite)打包安卓APP 完整最佳实践
android·vue
略略略咯咯12 小时前
LocalDateTime
android
℡枫叶℡12 小时前
Unity - 图集大小与内存占用
unity·图集内存
Co_Hui12 小时前
Android 系统服务的添加
android
_ZHOURUI_H_13 小时前
Unity MyFramework 用法说明(二十五):使用 AtlasManager 统一管理图集与 Sprite 引用
ui·unity·游戏引擎·unity3d·游戏开发
蜡台13 小时前
Flutter Container 与装饰完整讲解
android·javascript·flutter·dart