首先,您需要了解 API 如何响应您。它以始终以数据为前缀的 JSON 响应:{}。您可以使用 Newtonsoft.Json 和 JObject.Parse() 方法来查找数据标记并选择其属性。然后,您可以使用 Newtonsoft.Json 将其反序列化为对速率进行建模的类。费率具有代码、名称和费率属性。
让我们声明我们的类:
public class RateModel {
public string Code { get; set; }
public string Name { get; set; }
public decimal Rate { get; set; }
}
现在我们需要正确调用 API 以获得响应。我在一个小控制台应用程序中这样做了,如下所示:
private static void Main(string[] args) {
try {
string cryptoCurrencyCode = "BTC";
string countryCurrencyCode = "COP";
string uri = string.Format("https://bitpay.com/rates/{0}/{1}", cryptoCurrencyCode, countryCurrencyCode);
var client = new WebClient();
client.UseDefaultCredentials = true;
//Everything is returned inside of a "data" property, so let's select that token.
string data = JObject.Parse(client.DownloadString(uri)).SelectToken("data").ToString();
var rate = JsonConvert.DeserializeObject<RateModel>(data);
Console.WriteLine("1 {0} = {1} {2}", cryptoCurrencyCode, rate.Rate, countryCurrencyCode);
} catch (Exception ex) {
Console.WriteLine("Caught exception: {0}", ex.ToString());
} finally {
Console.WriteLine("Press Enter to exit.");
Console.ReadLine();
}
}
当然,如果我们只关心汇率而不关心显示任何其他数据,例如名称或代码,那么我们可以省略创建一个类来容纳其他数据,而只需选择该令牌本身:
var json = JObject.Parse(client.DownloadString(uri));
decimal rate = 0;
bool parsed = Decimal.TryParse(json.SelectToken("data").SelectToken("rate").ToString(), out rate);
if(!parsed) {
Console.WriteLine("Failed to parse the rate.");
} else {
Console.WriteLine("1 {0} = {1} {2}", cryptoCurrencyCode, rate, countryCurrencyCode);
}