简体   繁体   中英

c# Json to object list

I have a function that accesses a API and retrieves some Json values, these values are returned and pasted into a rich textbox. How am I able to convert this Json into a object list? The internet is filled with what i am asking but i'm not getting any wiser after reading and trying it all.

This is the function, URL is the Api link that retrieves the Json.

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;
            }
        }

This is the Json structure

{"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},

The first order of business is to use a library to parse the JSON. For this answer I use Newtonsoft.Json , one of the most used JSON libraries for .NET.

Then, the structure of the document you receive from the server should be identified. I'm just guessing here, but I assume it's something like the classes defined below. The JsonProperty is an attribute to specify the field name from the JSON document mapping to the property. It isn't necessary to specify this, only when your property names are different from the field names in the JSON document. In this case, unit_price does not match the standard .NET PascalCase naming convention for properties.

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; }
}

Once you have defined the class structure, you can let the library do all of the work. Look into the documentation for more details, here is how you would retrieve the list inside the method you already wrote.

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);
        }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM