当我使用Restsharp库的GET请求访问Json数据

时间:2017-07-08 06:36:47

标签: c# android json restsharp

我正在使用Restsharp库来进行Webservice操作。我试图从链接(http://www.mocky.io/v2/595616d92900003d02cd7191)访问数据并在Console中打印但我没有得到任何响应。当我使用断点时,Response显示为null 。这是我从链接获取数据的代码。

private async void GetItemsFromJSON()
    {
        IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
        IRestRequest request = new RestRequest(Method.GET);
        request.RequestFormat = DataFormat.Json;

        try
        {
            await Task.Run(() =>
            {
                IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
                var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
                Console.WriteLine(response.Content);

}

  public class ItemDetails
{
    public List<Itemschema> items { get; set; }
}
 public class Itemschema
{
    public int id { get; set; }
    public string sku { get; set; }
    public string name { get; set; }
    public int attribute_set_id { get; set; }
    public int price { get; set; }
    public int status { get; set; }
    public int visibility { get; set; }
    public string type_id { get; set; }
    public string created_at { get; set; }
    public string updated_at { get; set; }
    public int weight { get; set; }
}

我在这里遗漏了什么吗?我的架构类对应于Json数据如上所示。

1 个答案:

答案 0 :(得分:1)

我怀疑:

IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);

应该是:

IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);

http://www.mocky.io/v2/595616d92900003d02cd7191似乎返回一个包含模式数组的items属性。这比ItemDetails更接近List<ItemDetails>

此完整示例有效,因此您可能希望将其与代码进行比较:

using System;
using System.Collections.Generic;
using RestSharp;

namespace Test
{
    public class ItemDetails
    {
        public List<Itemschema> items { get; set; }
    }
    public class Itemschema
    {
        public int id { get; set; }
        public string sku { get; set; }
        public string name { get; set; }
        public int attribute_set_id { get; set; }
        public int price { get; set; }
        public int status { get; set; }
        public int visibility { get; set; }
        public string type_id { get; set; }
        public string created_at { get; set; }
        public string updated_at { get; set; }
        public int weight { get; set; }
    }

    public class Program
    {
        static void Main(string[] args)
        {
            IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
            IRestRequest request = new RestRequest(Method.GET);
            request.RequestFormat = DataFormat.Json;

            IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
            var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
            Console.WriteLine(Items.items.Count);
            Console.ReadLine();
        }
    }
}