0

1st time using World Trading data and JSONs in general. I am trying to retrieve the current price of a stock in C#

 using Newtonsoft.Json.Linq;
    static void get_stock_price()
    {
        string json;
        using (var web = new WebClient())
        {
            var url = $" https://www.worldtradingdata.com/api/v1/stock?symbol=AAPL,MSFT,HSBA.L&api_token=Io4R1hqd0rLONZcMp6tJgupqjVEyO0pVJAo65a6QlJjHjVBpEyt5nm73zZ5X";
            json = web.DownloadString(url);
            //How can I extract the price from the above?
        }

According to the developers documentation: the object returns a json structured like below:

{
"symbols_requested": 1,
"symbols_returned": 1,
"data": [
    {
        "symbol": "AAPL",
        "name": "Apple Inc.",
        "price": "174.33",
        "currency": "USD",
        "price_open": "173.71",
        "day_high": "175.30",
        "day_low": "173.17",
        "52_week_high": "233.47",
        "52_week_low": "142.00",
        "day_change": "0.10",
        "change_pct": "0.06",
        "close_yesterday": "174.23",
        "market_cap": "822014771033",
        "volume": "3171",
        "volume_avg": "28795902",
        "shares": "4715280000",
        "stock_exchange_long": "NASDAQ Stock Exchange",
        "stock_exchange_short": "NASDAQ",
        "timezone": "EST",
        "timezone_name": "America/New_York",
        "gmt_offset": "-18000",
        "last_trade_time": "2019-02-26 16:00:01"
    }
]
}

This is the site documentation: https://www.worldtradingdata.com/documentation#stock-and-index-real-time

This is the HTTP request link: https://www.worldtradingdata.com/api/v1/stock?symbol=AAPL,MSFT,HSBA.L&api_token=Io4R1hqd0rLONZcMp6tJgupqjVEyO0pVJAo65a6QlJjHjVBpEyt5nm73zZ5X

Could someone please guide me how to extract the price from the object?

lsama
  • 199
  • 3
  • 13
  • Did you even try to Google a solution to this? https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c – DavidG Feb 27 '19 at 12:20
  • 1
    Possible duplicate of [Load JSON text into class object in c#](https://stackoverflow.com/a/48023576/34092) – mjwills Feb 27 '19 at 12:25
  • I am stuck mostly on the fact I don't understand the line on davidG's link: dynamic stuff = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }"); I can't seem to figure out how to replace it with structure of my json – lsama Feb 27 '19 at 12:27

1 Answers1

2

You can use Newtonsoft.Json library to get price like this:

var trade = JsonConvert.DeserializeObject<dynamic>(json);
                var price = trade.data[0].price.ToString();
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62