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);
    }
相关推荐
阿巴斯甜15 小时前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker15 小时前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq952716 小时前
Andorid Google 登录接入文档
android
黄林晴17 小时前
告别 Modifier 地狱,Compose 样式系统要变天了
android·android jetpack
冬奇Lab1 天前
Android触摸事件分发、手势识别与输入优化实战
android·源码阅读
城东米粉儿1 天前
Android MediaPlayer 笔记
android
Jony_1 天前
Android 启动优化方案
android
阿巴斯甜1 天前
Android studio 报错:Cause: error=86, Bad CPU type in executable
android
张小潇1 天前
AOSP15 Input专题InputReader源码分析
android
_小马快跑_2 天前
Kotlin | 协程调度器选择:何时用CoroutineScope配置,何时用launch指定?
android