【问题标题】:c# Json to object listc# Json 到对象列表
【发布时间】:2015-04-02 00:38:13
【问题描述】:

我有一个访问 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 的代码与将 JSON 转换为列表的问题无关。您具体尝试过什么转换?这将与发布更相关......
  • @har07 我一直被指向序列化和其他使用结构。
  • 序列化有什么问题?避免序列化的任何具体原因?恕我直言,这是一种通过序列化将 JSON 转换为更友好的 .NET 对象的干净方式

标签: c# json object serialization


【解决方案1】:

首要任务是使用库来解析 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);
        }
    ...
}

【讨论】:

  • 如何访问我其他主类中的对象?
  • @KrijnvanderBurg 您如何在其他主类中访问您的字符串?这是方法调用的结果。
  • 你的意思是我如何访问 Json 字符串?我用这个作为值api_Request.GetApi("https://api.guildwars2.com/v2/commerce/listings/19684");
  • 你可以string xxx = api_Request....。而不是你可以这样做Listings xxx = api_Request....
  • 我使用的是富文本框。当试图应用你刚才说的我得到错误它不知道“.text”中的点。删除 .text 会返回错误:Cannot convert object to GW2_tradingPost.Listings 我认为这仅仅是因为您无法将对象发送到文本框?
猜你喜欢
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多