• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Odpowiedź "0" po próbie uzyskania danych z API

42 Warsaw Coding Academy
+1 głos
187 wizyt
pytanie zadane 11 sierpnia 2021 w C# przez CdxProj Użytkownik (910 p.)

Hej. Próbuję uzyskać konkretne dane z API, chciałbym otrzymać kurs bitcoina.. Oto plik JSON api którego używam:

https://pastebin.com/M3G0mWyt

Oto mój kod:

using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace CryptoApiTest
{
    class Program
    {
        HttpClient client = new HttpClient();
        static async Task Main(string[] args)
        {
            Program program = new Program();
            await program.getBtcData(); 
        }

        private async Task getBtcData()
        {
            string response = await client.GetStringAsync("Tutaj link do api z moim kluczem");

             Datum datum = JsonConvert.DeserializeObject<Datum>(response);

             Console.WriteLine(datum.price); 
        }
    }

    public class Config
    {
        public string data { get; set; }
        public string symbol { get; set; }
    }

    public class Usage
    {
        public int day { get; set; }
        public int month { get; set; }
    }

    public class Datum
    {
        public int id { get; set; }
        public string name { get; set; }
        public string symbol { get; set; }
        public float price { get; set; }
        public int price_btc { get; set; }
        public long market_cap { get; set; }
        public float percent_change_24h { get; set; }
        public float percent_change_7d { get; set; }
        public float percent_change_30d { get; set; }
        public float volume_24h { get; set; }
        public string max_supply { get; set; }
        public Timesery[] timeSeries { get; set; }
        public int social_dominance_calc_24h_previous { get; set; }
        public int social_contributors_calc_24h_previous { get; set; }
        public int url_shares_calc_24h_previous { get; set; }
        public int tweet_spam_calc_24h_previous { get; set; }
        public int news_calc_24h_previous { get; set; }
        public float average_sentiment_calc_24h_previous { get; set; }
        public int social_score_calc_24h_previous { get; set; }
        public int social_volume_calc_24h_previous { get; set; }
        public int alt_rank_30d_calc_24h_previous { get; set; }
        public int alt_rank_calc_24h_previous { get; set; }
        public int social_dominance_calc_24h { get; set; }
        public int social_dominance_calc_24h_percent { get; set; }
        public int social_contributors_calc_24h { get; set; }
        public float social_contributors_calc_24h_percent { get; set; }
        public int url_shares_calc_24h { get; set; }
        public float url_shares_calc_24h_percent { get; set; }
        public int tweet_spam_calc_24h { get; set; }
        public float tweet_spam_calc_24h_percent { get; set; }
        public int news_calc_24h { get; set; }
        public float news_calc_24h_percent { get; set; }
        public float average_sentiment_calc_24h { get; set; }
        public float average_sentiment_calc_24h_percent { get; set; }
        public int social_score_calc_24h { get; set; }
        public float social_score_calc_24h_percent { get; set; }
        public int social_volume_calc_24h { get; set; }
        public float social_volume_calc_24h_percent { get; set; }
        public int asset_id { get; set; }
        public int time { get; set; }
        public float open { get; set; }
        public float high { get; set; }
        public float low { get; set; }
        public float volume { get; set; }
        public int url_shares { get; set; }
        public int unique_url_shares { get; set; }
        public int tweets { get; set; }
        public int tweet_spam { get; set; }
        public int tweet_followers { get; set; }
        public int tweet_quotes { get; set; }
        public int tweet_retweets { get; set; }
        public int tweet_replies { get; set; }
        public int tweet_favorites { get; set; }
        public int tweet_sentiment1 { get; set; }
        public int tweet_sentiment2 { get; set; }
        public int tweet_sentiment3 { get; set; }
        public int tweet_sentiment4 { get; set; }
        public int tweet_sentiment5 { get; set; }
        public int tweet_sentiment_impact1 { get; set; }
        public int tweet_sentiment_impact2 { get; set; }
        public int tweet_sentiment_impact3 { get; set; }
        public int tweet_sentiment_impact4 { get; set; }
        public int tweet_sentiment_impact5 { get; set; }
        public int social_score { get; set; }
        public float average_sentiment { get; set; }
        public int sentiment_absolute { get; set; }
        public int sentiment_relative { get; set; }
        public int news { get; set; }
        public float price_score { get; set; }
        public int social_impact_score { get; set; }
        public int correlation_rank { get; set; }
        public float galaxy_score { get; set; }
        public float volatility { get; set; }
        public int alt_rank { get; set; }
        public int alt_rank_30d { get; set; }
        public int market_cap_rank { get; set; }
        public int percent_change_24h_rank { get; set; }
        public int volume_24h_rank { get; set; }
        public int social_volume_24h_rank { get; set; }
        public int social_score_24h_rank { get; set; }
        public int social_contributors { get; set; }
        public int social_volume { get; set; }
        public int social_volume_global { get; set; }
        public float social_dominance { get; set; }
        public long market_cap_global { get; set; }
        public float market_dominance { get; set; }
        public int medium { get; set; }
        public int youtube { get; set; }
        public int reddit_posts { get; set; }
        public int reddit_posts_score { get; set; }
        public int reddit_comments { get; set; }
        public int reddit_comments_score { get; set; }
        public string tags { get; set; }
        public float close { get; set; }
    }

    public class Timesery
    {
        public int asset_id { get; set; }
        public int time { get; set; }
        public float open { get; set; }
        public float close { get; set; }
        public float high { get; set; }
        public float low { get; set; }
        public float volume { get; set; }
        public long market_cap { get; set; }
        public int url_shares { get; set; }
        public int unique_url_shares { get; set; }
        public int? reddit_posts { get; set; }
        public int? reddit_posts_score { get; set; }
        public int? reddit_comments { get; set; }
        public int? reddit_comments_score { get; set; }
        public int tweets { get; set; }
        public int tweet_spam { get; set; }
        public int tweet_followers { get; set; }
        public int tweet_quotes { get; set; }
        public int tweet_retweets { get; set; }
        public int tweet_replies { get; set; }
        public int tweet_favorites { get; set; }
        public int tweet_sentiment1 { get; set; }
        public int tweet_sentiment2 { get; set; }
        public int tweet_sentiment3 { get; set; }
        public int tweet_sentiment4 { get; set; }
        public int tweet_sentiment5 { get; set; }
        public int tweet_sentiment_impact1 { get; set; }
        public int tweet_sentiment_impact2 { get; set; }
        public int tweet_sentiment_impact3 { get; set; }
        public int tweet_sentiment_impact4 { get; set; }
        public int tweet_sentiment_impact5 { get; set; }
        public int social_score { get; set; }
        public float average_sentiment { get; set; }
        public int sentiment_absolute { get; set; }
        public int sentiment_relative { get; set; }
        public object search_average { get; set; }
        public int news { get; set; }
        public float price_score { get; set; }
        public float social_impact_score { get; set; }
        public float correlation_rank { get; set; }
        public float galaxy_score { get; set; }
        public float volatility { get; set; }
        public int alt_rank { get; set; }
        public int alt_rank_30d { get; set; }
        public int market_cap_rank { get; set; }
        public int percent_change_24h_rank { get; set; }
        public int volume_24h_rank { get; set; }
        public int social_volume_24h_rank { get; set; }
        public int social_score_24h_rank { get; set; }
        public int? medium { get; set; }
        public int? youtube { get; set; }
        public int social_contributors { get; set; }
        public int social_volume { get; set; }
        public int price_btc { get; set; }
        public int social_volume_global { get; set; }
        public float social_dominance { get; set; }
        public long market_cap_global { get; set; }
        public float market_dominance { get; set; }
        public float percent_change_24h { get; set; }
    }

}

Co robię źle? Posiłkowałem się poradnikiem, wcześniej jak robiłem coś podobnego, ale do API z którego otrzymywałem dosłownie dwie zmienne, to wszystko działało w ten sposób poprawnie. Teraz za każdym razem jak uruchomię program, otrzymuję odpowiedź "0". Czym to jest spowodowane?

Myślałem że winą może być to, że próbuję zrobić stringa z floata, ale wcześniej robiłem string z inta i działało poprawnie, to mnie od takiego myślenia 'odciąga'.

1 odpowiedź

+3 głosów
odpowiedź 12 sierpnia 2021 przez PH03NIX Mądrala (6,130 p.)

Twój json jest całym jednym obiektem składającym się z config, usage i tablicy obiektów o nazwie data (jest tam wyłącznie 1 obiekt - [] oznaczają tablicę w jsonie). Ty starasz się go zdeserializować do obiektu Datum, który jest klasą określającą wyłącznie obiekt z tablicy o nazwie data.

Zwracane jest zero, ponieważ nowy obiekt Datum inicjalizowany jest domyślnymi wartościami (czyli 0 dla int, null dla string itd.).

W celu poprawnej deserializacji utworzyłem klasę Response odzwierciedlającą strukturę danych w jsonie, sam interesujący Cię obiekt jest pierwszym obiektem listy o nazwie data z tej klasy.

 HttpClient client = new HttpClient();
        static async Task Main(string[] args)
        {
            Program program = new Program();
            await program.getBtcData();
            Console.ReadKey();
        }

        private async Task getBtcData()
        {
            //string response = await client.GetStringAsync("Tutaj link do api z moim kluczem");
            var json = File.ReadAllText(@"C:\Users\xyz\Desktop\M3G0mWyt.json");

            Response response = JsonConvert.DeserializeObject<Response>(json);

            Console.WriteLine(response.data[0].price);
        }
    }

    public class Response
    {
        public Config config { get; set; }
        public Usage usage { get; set; }
        public List<Datum> data { get; set; }
    }

 

komentarz 12 sierpnia 2021 przez CdxProj Użytkownik (910 p.)

Dziękuję, Twoja odpowiedź była bardzo pomocna. Nie kopiowałem Twojego kodu, próbuję zrozumieć i zrobić to sam, ale mam jeszcze jedno małe pytanie. Po próbie uzyskania danych z linku z parametrem "BTC" otrzymuje dane poprawnie, "price bitcoina" wynosi ok. 45k$, dobowa zmiana procentowa -2,5%. Wszystko w normie, natomiast jak zmienię końcówkę linku z tego API na załóżmy ETH, lub LTC to otrzymuję wartości z innego pola, otrzymuje wartości z pola "price_btc" zamiast "price". Nie wiem czy w zależności od końcówki, struktura pliku Json może się jakoś zmienić(?). Wydawało mi się że odpowiedź JSON musi być zawsze taka sama, ale dla tej -> https://pastebin.com/M3G0mWyt odpowiedzi działa poprawnie, a dla tej -> https://pastebin.com/M1WaMZiy pokazuje już wartość z pola "price_btc" zamiast "price".

komentarz 12 sierpnia 2021 przez PH03NIX Mądrala (6,130 p.)
Nie podałeś z jakim api się komunikujesz (jak wygląda struktura odpowiedzi), ale tak api może zwrócić "cokolwiek" sobie programista wymyśli.

Jeżeli masz cene bitocina, a api dla reszty zwraca btc_price to z tego co widzę jest to ilość bitcoinów, którą możesz kupić za 1 jednostkę wybranej walut. Wystarczy więc przemnożyć price_btc * price (bitcoina) i masz cenę tej kryptowaluty.

Dla bitcoina = 1* 45k$ = 45k$

Dla LTC = 0.00376 * 44667$  ≈ 167.95$

Podobne pytania

0 głosów
0 odpowiedzi 307 wizyt
0 głosów
1 odpowiedź 1,334 wizyt
pytanie zadane 9 kwietnia 2019 w C# przez karol928 Początkujący (320 p.)
0 głosów
1 odpowiedź 854 wizyt
pytanie zadane 2 grudnia 2017 w C# przez Resho Nowicjusz (190 p.)

93,385 zapytań

142,384 odpowiedzi

322,540 komentarzy

62,745 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj

VMware Cloud PRO - przenieś swoją infrastrukturę IT do chmury
...