[英]Convert API String to JSON Object using NewtonSoft.Json
我讀過許多詢問類似問題的主題,但無法將它們結合在一起。
我有一個API在這里提供字符串: https : //apiv2.bitcoinaverage.com/constants/exchangerates/local
我想使此字符串可用和可訪問。 例如,將USD轉換為CAD匯率。
我在代碼中使用RestSharp和Newtonsoft JSON。
using Newtonsoft.Json;
using RestSharp;
首先,我使用http://json2csharp.com/創建了一個與字符串匹配的類(classes?)。 編輯:我現在已經解決了這個問題,並且必須按照修訂后的代碼正確嵌套類;
class Exrates
{
public Rates rates { get; set; }
public string time { get; set; }
public class Rates
{
public MXN Mxn { get; set; }
public ILS Ils { get; set; }
public EUR Eur { get; set; }
public BRL Brl { get; set; }
public PLN Pln { get; set; }
public MYR Myr { get; set; }
public SEK Sek { get; set; }
public AUD Aud { get; set; }
public IDR Idr { get; set; }
public TRY Try { get; set; }
public RUB Rub { get; set; }
public JPY Jpy { get; set; }
public CAD Cad { get; set; }
public USD Usd { get; set; }
public GBP Gbp { get; set; }
public NZD Nzd { get; set; }
public CZK Czk { get; set; }
public SGD Sgd { get; set; }
public class MXN
{
public string name { get; set; }
public string rate { get; set; }
}
public class ILS
{
public string name { get; set; }
public string rate { get; set; }
}
public class EUR
{
public string name { get; set; }
public string rate { get; set; }
}
public class BRL
{
public string name { get; set; }
public string rate { get; set; }
}
public class PLN
{
public string name { get; set; }
public string rate { get; set; }
}
public class MYR
{
public string name { get; set; }
public string rate { get; set; }
}
public class SEK
{
public string name { get; set; }
public string rate { get; set; }
}
public class AUD
{
public string name { get; set; }
public string rate { get; set; }
}
public class IDR
{
public string name { get; set; }
public string rate { get; set; }
}
public class TRY
{
public string name { get; set; }
public string rate { get; set; }
}
public class RUB
{
public string name { get; set; }
public string rate { get; set; }
}
public class JPY
{
public string name { get; set; }
public string rate { get; set; }
}
public class CAD
{
public string name { get; set; }
public string rate { get; set; }
}
public class USD
{
public string name { get; set; }
public string rate { get; set; }
}
public class GBP
{
public string name { get; set; }
public string rate { get; set; }
}
public class NZD
{
public string name { get; set; }
public string rate { get; set; }
}
public class CZK
{
public string name { get; set; }
public string rate { get; set; }
}
public class SGD
{
public string name { get; set; }
public string rate { get; set; }
}
}
}
然后,我調用了API,並將響應存儲在字符串中。
var btcAvgClient = new RestClient();
btcAvgClient.BaseUrl = new Uri("https://apiv2.bitcoinaverage.com/constants/exchangerates/local");
IRestResponse response;
var request = new RestRequest();
response = btcAvgClient.Execute(request);
string btcAvg = response.Content;
我相信還剩下1或2步,但我不太清楚。 現在如何將該字符串轉換為可用的字符串?
任何幫助表示贊賞!
首先,將數據模型修改為如下所示:
public class Rate
{
public string name { get; set; }
public decimal rate { get; set; }
}
public class RootObject
{
public Dictionary<string, Rate> rates { get; set; }
public string time { get; set; }
}
接下來,介紹以下擴展方法:
public static partial class RateExtensions
{
public static bool TryGetConversion(this Dictionary<string, Rate> rates, string from, string to, out decimal rate)
{
Rate fromRate;
Rate toRate;
if (rates == null || !rates.TryGetValue(from, out fromRate))
{
rate = 0;
return false;
}
if (!rates.TryGetValue(to, out toRate))
{
rate = 0;
return false;
}
rate = toRate.rate / fromRate.rate;
return true;
}
}
現在,您可以按以下方式執行類型化的請求。 鍵入的請求將自動將響應反序列化為所需的數據模型:
var btcAvgClient = new RestClient("https://apiv2.bitcoinaverage.com/");
var request = new RestRequest("constants/exchangerates/local");
// Execute the request and get the typed response
var response = btcAvgClient.Execute<RootObject>(request);
// Get the root object from the response.
RootObject data = response.Data;
並計算從USD到CAD的轉換,如下所示:
// Compute the converson from (e.g.) USD to CAD
var fromName = "USD";
var toName = "CAD";
decimal rate;
if (data.rates.TryGetConversion(fromName, toName, out rate))
{
Console.WriteLine("Conversion from {0} to {1} = {2}", fromName, toName, rate);
}
else
{
Console.WriteLine("Cannot get conversion from {0} to {1}.", fromName, toName);
}
在我的計算機上,此輸出
USD兌換CAD = 1.36245
經Google搜索確認,目前看來是正確的數字:
1美元等於1.36加元
筆記:
由於該API將來可能會返回不同的貨幣,但每種貨幣都有相同的數據,因此我將rates
定義為Dictionary<string, Rate> rates
。 該詞典將捕獲所有返回的貨幣匯率。
您的代碼將需要知道期望的貨幣名稱,但是我相信這些是標准的。
由於我們在這里進行貨幣換算,因此我將rate
定義為decimal
而不是string
。 串行器將自動將字符串字符串"rate"
反序列化為十進制。
為確保您的請求成功,請參閱使用RestSharp時如何慣用地處理HTTP錯誤代碼? 。
或者,您可以檢查“ response.ErrorException
,如“ 推薦用法”文檔頁面中所示。
如果需要發出async
請求,請參閱如何在Windows Phone 7上使用RestSharp實現ExecuteAsync? 。
RestSharp具有內置的JSON序列化器,但您可以根據需要使用Json.NET。 只需獲取response.Content
字符串並通過以下方式反序列化即可:
// Execute the request and get the untyped (string) response var response = btcAvgClient.Execute(request); // Get the root object from the response. RootObject data = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(response.Content);
應該是太根對象。
var beers = JsonConvert.DeserializeObject<RootObject>(response.Content);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.