Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from json api with c# using httpwebrequest?

Tags:

json

c#

api

I want to get all variables from https://api.coinmarketcap.com/v1/ticker/ in my c# console application. How can I do this?

I started with getting the whole page as a stream. What to do now?

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());
}
like image 397
D. Jung Avatar asked Jun 27 '17 08:06

D. Jung


People also ask

Can I use JSON in C?

Parsing JSON in C using microjson JavaScript Object Notation, or JSON, is a commonly used human-readable format for transmitting data objects as key-value pairs. Developed originally for server-browser communication, the use of JSON has since expanded into a universal data interchange format.

How can I get data from JSON?

Any JSON data can be consumed from different sources like a local JSON file by fetching the data using an API call. After getting a response from the server, you need to render its value. You can use local JSON files to do an app config, such as API URL management based on a server environment like dev, QA, or prod.

How do I get raw JSON data from REST API?

To receive JSON from a REST API endpoint, you must send an HTTP GET request to the REST API server and provide an Accept: application/json request header. The Accept header tells the REST API server that the API client expects JSON.


1 Answers

First you need a custom class to use for deserialization:

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

Next, you can use Newtonsoft Json, a free JSON serialization and deserialization framework in the following way to get your items (include the following using statements):

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
}

Finally, the list of elements is stored in items.

like image 82
Keyur PATEL Avatar answered Nov 13 '22 15:11

Keyur PATEL