C# - Api do DataGridView

0

Witam, chciałbym aby stąd https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd wyświetlić w DataGridView.

kod niestety nie działa

 static async Task<DataTable> Consume()
        {
            DataTable dt = new DataTable();
            var client = new HttpClient();
            client.BaseAddress = new Uri("https://api.coingecko.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var response = await client.GetAsync("api/v3/simple/price?ids=bitcoin&vs_currencies=usd").ConfigureAwait(false);
            if(response.IsSuccessStatusCode)
            {
                dynamic result = await response.Content.ReadAsStringAsync();
                dt = (DataTable)JsonConvert.DeserializeObject(result, typeof(DataTable));
            }
            return dt;
        }
   private async void button6_Click(object sender, EventArgs e)
        {
            DataTable x = await Consume();
            dataGridView4.DataSource = x;
        }
0

Co to znaczy Nie działa? Debuggowałeś go? Co jest w result?

0

Tak debuggowałem, result jest null

0

Możesz wrzucić cały response?

4

Reponse twojego API to coś takiego: {"bitcoin":{"usd":34923}}, a próbujesz zrobić dt = (DataTable)JsonConvert.DeserializeObject(result, typeof(DataTable)); - tak to się nie da, dlatego dostajesz null.

Zdeserializuj sobie odpowiedź API do jakiegoś własnego typu, a potem ręcznie zbuduj DataTable, w stylu:

DataTable dt = new DataTable(); 
dt.Clear();
dt.Columns.Add("USD");
DataRow r = dt.NewRow();
r["USD"] = wartoscZObiektuzAPI;
dt.Rows.Add(r);

1 użytkowników online, w tym zalogowanych: 0, gości: 1