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);
    }
相关推荐
androidwork9 小时前
Android LinearLayout、FrameLayout、RelativeLayout、ConstraintLayout大混战
android·java·kotlin·androidx
每次的天空9 小时前
Android第十三次面试总结基础
android·面试·职场和发展
wu_android9 小时前
Android 相对布局管理器(RelativeLayout)
android
李斯维11 小时前
循序渐进 Android Binder(二):传递自定义对象和 AIDL 回调
android·java·android studio
androidwork11 小时前
OkHttp 3.0源码解析:从设计理念到核心实现
android·java·okhttp·kotlin
像风一样自由12 小时前
【001】frida API分类 总览
android·frida
casual_clover12 小时前
Android 之 kotlin 语言学习笔记四(Android KTX)
android·学习·kotlin
移动开发者1号14 小时前
Android 大文件分块上传实战:突破表单数据限制的完整方案
android·java·kotlin
移动开发者1号14 小时前
单线程模型中消息机制解析
android·kotlin
不伤欣14 小时前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式