0

so i want to get bitcoin price from a URL and see it in a label in my form.

URL

i tried to make a class for it with the code

public string price { get; set; }

but i don't know what to do after that, i searched a lot in google but they all show the result in list and etc

Oliver
  • 83
  • 1
  • 10
  • 1
    Does this answer your question? [Deserialize JSON with C#](https://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp) – Sinatr Aug 07 '20 at 11:56

4 Answers4

1

To deserialize, first you need to make a class with the attributes the JSON has. This page will help you a lot in that.

Once you have a class, you need to deserialize your JSON into that class. In C# I like to use JsonConvert from the library Newtonsoft.Json, you need to import it.

The method that deserializes it is JsonConvert.DeserializeObject.

One little example, let's say your class is called Bitcoin, then you would have to do it that way :

var myBitcoin = JsonConvert.DeserializeObject<Bitcoin>(yourJson);

EDIT: To pull your json from an URL you can use Webclient DownloadString method.

var myjson = new WebClient().DownloadString("url");

This post may also help you.

Óscar López
  • 328
  • 2
  • 12
0

This should be your class.

   public class APIResponse
    {
        public string symbol { get; set; } 
        public string price { get; set; } 
    }

Then in your function add these lines.

APIResponse response = new APIResponse();

response = JsonConvert.DeserializeObject<APIResponse>();

myPriceLabel.Text = response.price;

What did we do? We created a C# model same as the Json Data model and we took JSON data and converted it to APIResponse type so we can access it and use it as we like.

Arif Mucahid
  • 46
  • 1
  • 6
0

It can be achieved simply by converting the Json with generic object

var myBitcoin = JsonConvert.DeserializeObject<object>(yourJson);
Sh.Imran
  • 1,035
  • 7
  • 13
0

thank you all for answering but i found the solution!

the code should be like this

string url = "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT";
        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString(url);
            JavaScriptSerializer oJS = new JavaScriptSerializer();
            PriceClass obj = new PriceClass();
            obj = oJS.Deserialize<PriceClass>(json);

            BTCPrice_Label.Text = obj.price;

        }

and the class should be like this

using System;


    public class PriceClass
    {
        public string symbol { get; set; }
        public string price { get; set; }
    }
Oliver
  • 83
  • 1
  • 10