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

文章讲述了如何在Unity应用中使用LitJson库来读取和保存JSON数据,包括从文件中加载数据到字典以及将字典内容保存回JSON文件的过程。
摘要由CSDN通过智能技术生成

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

// 创建一个字典用来给读取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

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);
    }
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值