簡體   English   中英

c#Json到對象列表

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM