[英]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.