连接到REST Api并检索JSON

时间:2018-09-29 01:04:06

标签: c# api

我正在连接到API,但是在Json中检索数据没有任何运气。我有不同的端点可以使用,但似乎无法正常工作。我相信/ products应该能给我整个清单,但是运气不好。

class Program 
{
    static void Main(string[] args)
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            //go get the data

            string token = "auth token";

            client.BaseAddress = new Uri("");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            Console.WriteLine("GET");
            HttpResponseMessage response = await client.GetAsync("/products/6");
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Connected");
                RootObject product = await response.Content.ReadAsAsync<RootObject>();


                Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", product.data.id,product.data.name,product.data.sort,product.data.designation_id,product.data.designation_id);
            }
            else
            {
                Console.WriteLine("Failed");
                Console.WriteLine(response.Headers);
            }
        }
    }
}

我在控制台上得到的响应是:

0
1/1/0001 12:00:00 AM
1/1/0001 12:00:00 AM

产品类别:

    public class RootObject
    {
        public Product data { get; set; }
    }
    public class Product
    {
        public int id { get; set; }
        public object designation_id { get; set; }
        public string name { get; set; }
        public object alternate_name { get; set; }
        public object description { get; set; }
        public int sort { get; set; }
        public string created_at { get; set; }
        public string updated_at { get; set; }
    }

测试与邮递员的连接时得到的响应如下:

{
    "data": {
        "id": 6,
        "designation_id": null,
        "name": "Multirate Fork Springs Kit",
        "alternate_name": null,
        "description": null,
        "sort": 0,
        "created_at": "2016-06-17 20:47:51",
        "updated_at": "2018-05-25 09:40:50"
    }
}

1 个答案:

答案 0 :(得分:0)

nuget Newtonsoft.Json

,您可以执行以下操作:

rm -r node_modules
npm install

在客户端,使用响应

  using Newtonsoft.Json;

这真的很好,只要您的产品类别具有所有正确的属性,您应该就可以使用!