[英]C# Deserialize JSON to Object
我對C#程序有一點問題。 這是我在C#中的第一個程序所以請 - 請原諒:)
我想將我的json文件反序列化為對象,但我不知道應該如何構建我的類。 我正在使用Newtonsoft JSON lib。
JSON文件:
http://api.nbp.pl/api/exchangerates/tables/A/last/?format=json
Form1.cs中:
private void button1_Click(object sender, EventArgs e)
{
CurrencyCodeValues k = new CurrencyCodeValues();
WebClient myWebClient = new WebClient();
dynamic result = myWebClient.DownloadString("http://api.nbp.pl/api/exchangerates/tables/A/last/?format=json");
IList<CurrencyCodeValues> m = JsonConvert.DeserializeObject<CurrencyCodeValues>(result);
}
將Class1.cs:
class CurrencyCodeValues
{
public string table { get; set; }
public string no { get; set; }
public string effectiveDate { get; set; }
public List<rates_> rates { get; set; }
}
public class rates_
{
public string currency { get; set; }
public string code { get; set; }
public float mid { get; set; }
}
錯誤信息:
無法將當前JSON數組(例如[1,2,3])反序列化為類型“WindowsFormsApplication4.CurrencyCodeValues”,因為該類型需要JSON對象(例如{“name”:“value”})才能正確反序列化。 要修復此錯誤,請將JSON更改為JSON對象(例如{“name”:“value”})或將反序列化類型更改為數組或實現集合接口的類型(例如ICollection,IList),例如List從JSON數組反序列化。 JsonArrayAttribute也可以添加到類型中以強制它從JSON數組反序列化。 路徑'',第1行,第1位。
正如您的錯誤消息所示,您的課程應如下所示
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string table { get; set; }
public string no { get; set; }
public string effectiveDate { get; set; }
public Rate[] rates { get; set; }
}
public class Rate
{
public string currency { get; set; }
public string code { get; set; }
public float mid { get; set; }
}
然后像它一樣去除它
JsonConvert.DeserializeObject<Rootobject>(result);
如果您不確定類模型必須與特定的json結構匹配,Visual Studio(自VS2013 Update 2以來)具有非常有用的功能。 您可以復制json字符串,轉到Visual Studio,然后單擊編輯 - >選擇性粘貼 - >將JSON粘貼為類。
現在,Visual Studio將構成一個適合的類模型。
在你的情況下,它看起來像這樣(就像Mohit Shrivastava已經建議的那樣):
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string table { get; set; }
public string no { get; set; }
public string effectiveDate { get; set; }
public Rate[] rates { get; set; }
}
public class Rate
{
public string currency { get; set; }
public string code { get; set; }
public float mid { get; set; }
}
在反序列化json時,你需要使用基本結構和自定義clases,因為json不支持列表,映射和其他保存數據並在其上做一些邏輯的結構。 這意味着你不能使用List<rates_>
你需要使用rates_[]
也就像Mohit Shrivastava sugested一樣 - 你需要添加Wrapper類,因為你請求返回CurrencyCodeValues
對象的數組,而不是單個對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.