如何使用httpwebrequest使用c#从json api获取数据?

时间:2017-06-27 08:34:18

标签: c# json api

我想从我的c#控制台应用程序中获取https://api.coinmarketcap.com/v1/ticker/的所有变量。 我怎么能这样做?

我开始将整个页面作为一个流。现在该怎么办?

private static void start_get()
{
    HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create
        (string.Format("https://api.coinmarketcap.com/v1/ticker/"));

    WebReq.Method = "GET";

    HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

    Console.WriteLine(WebResp.StatusCode);
    Console.WriteLine(WebResp.Server);

    Stream Answer = WebResp.GetResponseStream();
    StreamReader _Answer = new StreamReader(Answer);
    Console.WriteLine(_Answer.ReadToEnd());
}

2 个答案:

答案 0 :(得分:11)

首先,您需要一个用于反序列化的自定义类:

public class Item
{
    public string id { get; set; }
    public string name { get; set; }
    public string symbol { get; set; }
    public string rank { get; set; }
    public string price_usd { get; set; }
    [JsonProperty(PropertyName = "24h_volume_usd")]   //since in c# variable names cannot begin with a number, you will need to use an alternate name to deserialize
    public string volume_usd_24h { get; set; }
    public string market_cap_usd { get; set; }
    public string available_supply { get; set; }
    public string total_supply { get; set; }
    public string percent_change_1h { get; set; }
    public string percent_change_24h { get; set; }
    public string percent_change_7d { get; set; }
    public string last_updated { get; set; }
}

接下来,您可以使用Newtonsoft Json,一个免费的JSON序列化和反序列化框架,通过以下方式获取您的项目(包括以下using语句):

using System.Net;
using System.IO;
using Newtonsoft.Json;

private static void start_get()
{
    HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("https://api.coinmarketcap.com/v1/ticker/"));

    WebReq.Method = "GET";

    HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

    Console.WriteLine(WebResp.StatusCode);
    Console.WriteLine(WebResp.Server);

    string jsonString;
    using (Stream stream = WebResp.GetResponseStream())   //modified from your code since the using statement disposes the stream automatically when done
    {
       StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
       jsonString = reader.ReadToEnd();
    }

    List<Item> items = JsonConvert.DeserializeObject<List<Item>>(jsonString);

    Console.WriteLine(items.Count);     //returns 921, the number of items on that page
}

最后,元素列表存储在items中。

答案 1 :(得分:0)

Keyur PATEL工作的简化版本。

static void GetCoinValues()         {

        string json = new WebClient().DownloadString("https://api.coinmarketcap.com/v1/ticker/");

        List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);

        foreach (var item in items)
        {
            Console.WriteLine("ID: " + item.id.ToUpper());
            Console.WriteLine("Name: " + item.name.ToUpper());
            Console.WriteLine("Symbol: " + item.symbol.ToUpper());
            Console.WriteLine("Rank: " + item.rank.ToUpper());
            Console.WriteLine("Price (USD): " + item.price_usd.ToUpper());
            Console.WriteLine("\n");
        }
    }




}