不知道如何在 C# 中使用这个 API

Can't figure how to consume this API in C#

请原谅我的知识匮乏,我是一名数据库专家,尽管我前一段时间对 C# 略有涉猎。我正在想办法得到这个 API 运行。

我想喝的 API 来自 https://rapidapi.com/api-sports/api/api-nba/。几乎没有任何文档可以指导我。

这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using unirest_net.http;
using unirest_net;

namespace NBA_test
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Start ...");

            Task<HttpResponse<MyClass.RootObject>> response = Unirest.get("https://api-nba-v1.p.rapidapi.com/gameDetails/5162")
            .header("X-RapidAPI-Host", "api-nba-v1.p.rapidapi.com")
            .header("X-RapidAPI-Key", "myKey")
            .asJsonAsync<MyClass.RootObject>();

            var status = response.Status;

            Console.WriteLine("End ....");
        }
    }

    public class MyClass
    {
        public class Result
        {
            public string seasonYear { get; set; }
            public int gameId { get; set; }
            public string arena { get; set; }
        }

        public class RootObject
        {
            public List<Result> results { get; set; }
        }
    }
}

var status 从 Created 变为 运行 然后就是这样,程序关闭。没有错误消息,但我不知道如何从 API 中获取 JSON。我知道我错过了什么,但不知道是什么。

您正在使用 sync main 方法的控制台应用程序中。您不应在 sync 方法中调用 async 方法。我把你的 async 电话变成了 sync 电话:

    public static void Main(string[] args)
    {
        Console.WriteLine("Start ...");

        var response = Unirest.get("https://api-nba-v1.p.rapidapi.com/gameDetails/5162")
        .header("X-RapidAPI-Host", "api-nba-v1.p.rapidapi.com")
        .header("X-RapidAPI-Key", "myKey")
        .asJson<RootObject>();

        var status = response.Status;

        Console.WriteLine("End ....");
    }

你可能还会问你反序列化的JSON在哪里?

根据Unirest docs

Response Upon recieving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details.

.Code - HTTP Response Status Code (Example 200) .Headers - HTTP Response Headers .Body - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays. .Raw - Un-parsed response body

基本上,您可以像这样访问结果:

if (response.Code == 200) // Success, OK in HTTP Codes
{
  response.Body; // which body has the type of MyClass.RootObject
}

完整示例:

        public static void Main(string[] args)
        {
            Console.WriteLine("Start ...");

            var response = Unirest.get("https://api-nba-v1.p.rapidapi.com/gameDetails/5162")
            .header("X-RapidAPI-Host", "api-nba-v1.p.rapidapi.com")
            .header("X-RapidAPI-Key", "myKey")
            .asJson<RootObject>();

            if (response.Code == 200) // Success, OK in HTTP Codes
            {
              response.Body; // which body has the type of MyClass.RootObject
            }

            Console.WriteLine("End ....");

            Console.ReadLine(); // to force command line stay up for an input and not close applicaiton immediately aftter runing it.
        }

更新 1:

这是 Unirest 在 .NET 上的实时和工作 Fiddle:

https://dotnetfiddle.net/EZDopa

正如其他人所指出的,您需要添加一些类似的等待语句。我对 api 进行了多次调用,这些调用在我的一个应用程序中需要时间来处理。根据我更新的其他评论,允许在您等待呼叫返回时执行逻辑。您的代码的编辑是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using unirest_net.http;
using unirest_net;

namespace NBA_test
{
class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Start ...");
        //the added Wait() causes the thread to hold until the task is finished.
        Task<HttpResponse<MyClass.RootObject>> response = Unirest.get("https://api-nba-v1.p.rapidapi.com/gameDetails/5162")
        .header("X-RapidAPI-Host", "api-nba-v1.p.rapidapi.com")
        .header("X-RapidAPI-Key", "myKey")
        .asJsonAsync<MyClass.RootObject>();


        //if need to perform other logic while you are waiting
        while(response.Status == TaskStatus.Running)
        {
         // perform other logic like gui here
        }
        var status = response.Status;

        Console.WriteLine("End ....");
    }
}

public class MyClass
{
    public class Result
    {
        public string seasonYear { get; set; }
        public int gameId { get; set; }
        public string arena { get; set; }
    }

    public class RootObject
    {
        public List<Result> results { get; set; }
    }
}

}

您可以使用 httpClient

   using (var httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36");
            var response = httpClient.GetStringAsync(new Uri(url)).Result;
            var releases = JArray.Parse(response);
        }

原来 API 的文档有缺陷。我设法通过简单地使用字符串(和 Newtonsoft 的 Json.NET)使其工作。感谢@AliBahrami 的帮助。代码现在看起来像这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using unirest_net.http;
using unirest_net;
using Newtonsoft.Json.Linq;

namespace NBA_test
{
    public class Program
    {

        public static void Main(string[] args)
        {

            Console.WriteLine("Start of Program...");

            HttpResponse<string> response = Unirest.get("https://api-nba-v1.p.rapidapi.com/gameDetails/9999")
            .header("X-RapidAPI-Host", "api-nba-v1.p.rapidapi.com")
            .header("X-RapidAPI-Key", "myKey")
            .asJson<string>();

            var result = response.Body;

            JObject parsedString = JObject.Parse(result);

            RootObject myGame = parsedString.ToObject<RootObject>();

            // Get game id
            Console.WriteLine(myGame.results[0].gameId);

            Console.WriteLine("End of Program....");
        }
    }
}