當我運行下面的代碼時,它回傳一個錯誤。我不確定如何解決這個問題。我只需要將這個JSON轉換為C#類而不出錯。
下面是自定義的C#物件映射到JSON obj:
public class ExchangeRate
{
public string Disclaimer { get; set; }
public string License { get; set; }
public string Timestamp { get; set; }
public string Base { get; set; }
public string Rates { get; set; }
這是回傳錯誤的api呼叫:
public static async Task<List> GetLatest(string url) {
var client = new HttpClient()。
string results = await client.GetStringAsync(url);
List<ExchangeRate> ratesList = JsonConvert.DeserializeObject<List<ExchangeRate>>(results)。
return ratesList;
}
uj5u.com熱心網友回復:
你的C#類模型與傳入的JSON資料結構不匹配。Rates是一個專案陣列,但你在C#模型中把它當作一個字串。時間戳是一個數字,但你在C#模型中把它當成了一個字串。
public class ExchangeRate
{
public string Disclaimer { get; set; }
public string License { get; set; }
public int Timestamp { get; set; }
public string Base { get; set; }
public Dictionary<string, double> Rates { get; set; }
uj5u.com熱心網友回復:
例子中的JSON不是一個串列,它是一個單一的物件,這在例外資訊中被指定了
...因為這個型別需要一個JSON陣列
,否則它周圍會有[ ]表示一個陣列(可以反序列化為串列)。另外,你的模型是有缺陷的,因為Rates不是一個字串,而是一個物件,而Timestamp不是一個字串,而是一個以刻度表示的日期時間的長度。改變你的模型,就像這樣:
public class ExchangeRate
{
/decorate your properties since the json string uses lowercase[/span]。
[JsonProperty("disclaimer")]
public string Disclaimer { get; set; }
[JsonProperty("license"/span>)]
public string License { get; set; }
[JsonProperty("timestamp"/span>)]
public long Timestamp { get; set; }
[JsonProperty("base"/span>)]
public string Base { get; set; }
[JsonProperty("rate")]
public Rates { get; set; }
}
public class Rates; }
{
//創建利率類的屬性。
}
或者讓費率屬性成為Dictionary<string, decimal>,NOTE:如果任何鍵被重復,這可能會失敗。
public class ExchangeRate
{
/decorate your properties since the json string uses lowercase[/span]。
[JsonProperty("disclaimer")]
public string Disclaimer { get; set; }
[JsonProperty("license"/span>)]
public string License { get; set; }
[JsonProperty("timestamp"/span>)]
public long Timestamp { get; set; }
[JsonProperty("base"/span>)]
public string Base { get; set; }
[JsonProperty("rate")]
public Dictionary<string, decimal> Rates { get; set; }
把你的代碼改成這樣:
ExchangeRate rate = JsonConvert.DeserializeObject<ExchangeRate>(results)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/309499.html
標籤:


