c# - API GET 方法不在 Xamarin Forms 的属性中存储数据
问题描述
数据正在从 API 中成功检索,正如我在这里看到的那样, 响应 然后转到jsonstring,但永远不会到达CantGet变量
我需要将它存储在我的财产中,以便我可以使用该值。
这是我的 API 返回:[{"CantPremio":"70"}
然后这是我的财产:
using System;
using System.Collections.Generic;
using System.Text;
namespace ServLottery
{
public class GetCantPremio
{
public long CantPremio { get; set; }
}
}
这是获取任务
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
namespace ServLottery
{
public class RestClient
{
HttpClient client = new HttpClient();
public async Task<T> Get<T>(string URL)
{
try
{
var response = await client.GetAsync(URL);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var jsonstring = await response.Content.ReadAsStringAsync();
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonstring);
}
}
catch
{
}
return default(T);
}
}
}
最后是调用:
private async void GetCantDisponible()
{
try
{
RestClient client = new RestClient();
var CantGet = await client.Get<GetCantPremio>("https://servicentroapi.azurewebsites.net/api/GetNumber");
if (CantGet != null)
{
PremiosCantLocal = CantGet.CantPremio.ToString();
}
}
catch (Exception ex)
{
throw ex;
}
}
解决方案
您正在访问的 api 正在返回一个数组。所以你必须反序列化的不是一个简单的对象,而是一个列表。
return Newtonsoft.Json.JsonConvert.DeserializeObject<List<T>>(jsonstring);
用这一行替换反序列化的行。应该解决问题
推荐阅读
- javascript - 传递 onChange 函数已经参数复选框
- react-native - React Native (0.59.10) — 如何在运行测试时删除 `useNativeDriver`(但不在实际应用程序中)
- python-3.x - 如何将 random.sample 输出到变量?
- servicenow - 我应该在 ServiceNow 中使用范围应用程序还是只在全局范围内开发
- reactjs - 在项目中使用 css 反应 BootStrap 版本问题
- android - 如何更改导航图标的颜色和 ActionMode 的默认文本
- java - 如果将常量返回到哈希码并且返回 false 到 equals 会发生什么
- c# - 简化 LINQ - 使用两个不同的 where 子句对 Col 求和两次
- android - 滑动后如何检测点击recyclerview项目下方的视图?
- replace - 有没有更好的方法来转义 POSIX sh 中字符串中的斜杠