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

标签 c# json api

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

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

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

最佳答案

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

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 中。

关于c# - 如何使用 c# 使用 httpwebrequest 从 json api 获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44775645/

相关文章:

c# - LINQ 时间戳 - 自动更新时间戳列?

c# - 北风数据集

json - ReJson - 从第二层键的匹配中检索所有值

android - AIR - 在 Android 上打开文件(openWithDefaultApplication() 替代方案)

API认证设计

c# - 将 LINQ-to-SQL 对象转换为模型对象的好方法是什么?

c# - Tfs 格式文件 C# 项目

json - JAXB 在对象图中检测到一个循环

java - Elastic Search 5 中的复杂搜索查询

javascript - PerformanceNavigationTiming API 的特征检测