当前位置:   article > 正文

Unity将数据保存为本地Json文件_unity 导出 json

unity 导出 json
/// 判断文件是否存在
public static bool CheckFileExists(string filePath)
    {
        return File.Exists(filePath);
    }
    /// <summary>
    /// 保存json为文件
    /// </summary>
    /// <param name="jsonData"></param>
    /// <param name="filePath"></param>
    public static void SaveJsonToFile(string jsonString, string filePath)
    {
        JsonData jsonData = JsonMapper.ToObject(jsonString);

        bool fileExists = CheckFileExists(filePath);
        if (fileExists)
        {
            Debug.LogError("文件存在。");
        }
        else
        {
            using (StreamWriter sw = new StreamWriter(filePath))
            {
                sw.Write(jsonData.ToJson());
            }
            Debug.LogError("文件不存在。保存成功");
        }
       
    }
///请求接口 

    IEnumerator UnityWebRequestPost(string url, Dictionary<string, string> formdata, Action<string> textCallBack)
    {
        WWWForm wWForm = new WWWForm();
        foreach (var item in formdata)
        {
            wWForm.AddField(item.Key, item.Value);
        }
        using (UnityWebRequest request = UnityWebRequest.Post(url, wWForm))
        {
            // request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();


            yield return request.SendWebRequest();
            if (request.isHttpError || request.isNetworkError)
            {
                Debug.LogError(request.error);

            }
            else
            {
                string result = request.downloadHandler.text;
                string filePath = Application.dataPath + "/example.json";
                SaveJsonToFile(result, filePath);
                textCallBack?.Invoke(result);
            }
        }
    }
// 请求数据
  public void StartGetweather()
    {
        Dictionary<string, string> formDic = new Dictionary<string, string>();
        formDic.Add("deviceId", "408aee9882453566018247d34b090002");
        StartCoroutine(UnityWebRequestPost(url, formDic, text =>
          {
              Debug.Log("请求结果:" + text);
              Root root = JsonMapper.ToObject<Root>(text);
              JsonData jsonData = JsonMapper.ToObject(text);
              for (int i = 0; i < root.GetDatas.Count; i++)
              {
                  Debug.Log(root.GetDatas[i].GetDevStatus);
              }
             
        }));


    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号