/// 判断文件是否存在
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);
}
}));
}
Unity将数据保存为本地Json文件
猜你喜欢
转载自blog.csdn.net/weixin_42430280/article/details/132690616
今日推荐
周排行