[英]c# Json to object list
我有一个访问API并检索一些Json值的函数,这些值被返回并粘贴到富文本框中。 我如何能够将此Json转换为对象列表? 互联网上充满了我所要问的内容,但是在阅读并尝试所有内容后,我并没有变得更明智。
这是函数,URL是检索Json的Api链接。
public string GetApi(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
这是Json结构
{"id":19684,"buys":[{"listings":10,"unit_price":94,"quantity":2498},{"listings":42,"unit_price":93,"quantity":10398},{"listings":139,"unit_price":92,"quantity":34501},{"listings":8,"unit_price":91,"quantity":1939},{"listings":38,"unit_price":90,"quantity":9270},{"listings":7,"unit_price":89,"quantity":1266},{"listings":43,"unit_price":88,"quantity":10565},{"listings":23,"unit_price":87,"quantity":5476},{"listings":80,"unit_price":86,"quantity":19827},
首先要做的是使用库来解析JSON。 对于此答案,我使用Newtonsoft.Json ,这是.NET最常用的JSON库之一。
然后,应该确定您从服务器收到的文档的结构。 我只是在这里猜测,但我认为它类似于下面定义的类。 JsonProperty
是一个属性,用于指定从JSON文档映射到该属性的字段名称。 仅当您的属性名称与JSON文档中的字段名称不同时,才需要指定此名称。 在这种情况下, unit_price
与属性的标准.NET PascalCase命名约定不匹配。
public class Listings
{
[JsonProperty(PropertyName = "id")]
public int Id { get; set; }
public List<Buy> Buys { get; private set; }
public Listings()
{
Buys = new List<Buy>();
}
}
public class Buy
{
[JsonProperty(PropertyName = "listings")]
public int Listings { get; set; }
[JsonProperty(PropertyName = "unit_price")]
public int UnitPrice { get; set; }
[JsonProperty(PropertyName = "quantity")]
public int Quantity { get; set; }
}
一旦定义了类结构,就可以让该库完成所有工作。 查看文档以获取更多详细信息,这是如何在已编写的方法内检索列表。
public Listings GetApi(string url)
{
...
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
return serializer.Deserialize<Listings>(jsonReader);
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.