Lukáš Trkan
Lukáš Trkan

Reputation: 41

C# - better way to get data from API?

I am trying to create currency converter from ETH to CZK and I am using APIs to get the balance of my account and an actual exchange rate of CZK.

I am using this:

WebClient client = new WebClient();
string downloadString = client.DownloadString("https://api.nanopool.org/v1/eth/balance/0x1b0cab6db1672349b8f8a6d8d8903ab58ae0d734");
//Console.WriteLine(downloadString);
downloadString = downloadString.Replace('.', ',');
//Console.WriteLine(downloadString);
string[] first = downloadString.Split(':');
string ETH = first[2].Remove(first[2].Length-1);
Console.WriteLine(ETH);
string downloadString2 = client.DownloadString("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=CZK");
downloadString2 = downloadString2.Replace('.', ',');
string[] second = downloadString2.Split(':');
string CZK = second[1].Remove(second[1].Length - 1);
Console.WriteLine(CZK);
float eth = float.Parse(ETH);
float czk = float.Parse(CZK);
Console.WriteLine("You have {0} CZK", eth * czk);

Is there a better way to remove every thing else from API then numbers?
Thanks

Upvotes: 0

Views: 1293

Answers (3)

Lukas.

Why you don´t convert to an object? I think you can create a classes. As here:

   public class Link1Data
   {
       public bool status { get; set; }
       public float data { get; set; }
   }


   public class Link2CZK
   {
       public float CZK { get; set; }
   }

Then change your code to:

   WebClient webClient = new WebClient();
   var data = webClient.DownloadString("https://api.nanopool.org/v1/eth/balance/0x1b0cab6db1672349b8f8a6d8d8903ab58ae0d734");
   var ethData = JsonConvert.DeserializeObject<Link1Data>(data);

   var data2 = webClient.DownloadString("https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=CZK");
   var czkData = JsonConvert.DeserializeObject<Link2CZK>(data2);

   Console.WriteLine("You have {0} CZK", ethData.data * czkData.CZK);

Based on: How to convert a Stream into an object

I did not test. ;-)

Upvotes: 0

Stewart_R
Stewart_R

Reputation: 14515

The string you are getting back is JSON. Use a library to deserialize it.

Newtonsoft's JSON.net is popular

You can then do something like:

string responseString = client.DownloadString("https://api.nanopool.org/v1/eth/balance/0x1b0cab6db1672349b8f8a6d8d8903ab58ae0d734")
dynamic reponseObj = JsonConvert.DeserializeObject<dynamic>(repsonseString);
double data = responseObj.data;

Upvotes: 3

Bestter
Bestter

Reputation: 878

It's return a JSON. You can parse it with a JSON parser.

See: https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-serialize-and-deserialize-json-data

Upvotes: 3

Related Questions