首页 > 解决方案 > 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;
            }

        }

标签: c#apixamarin.formsget

解决方案


您正在访问的 api 正在返回一个数组。所以你必须反序列化的不是一个简单的对象,而是一个列表。

return Newtonsoft.Json.JsonConvert.DeserializeObject<List<T>>(jsonstring);

用这一行替换反序列化的行。应该解决问题


推荐阅读