C# – Uso de HttpClient para devolver un DataTable

Si usamos una API-REST que nos devuelve un Datatable, es necesario deserializar el JSON obtenido.

El siguiente ejemplo nos muestra como hacerlo:

using System;
using System.Data;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json; // You'll need to install the Newtonsoft.Json NuGet package

class Program
{
    static async Task Main()
    {
        // Create an instance of HttpClient
        using (HttpClient httpClient = new HttpClient())
        {
            try
            {
                // Replace the URL with the actual URL 
                // of the web service or API that returns a DataTable
                string apiUrl = "https://example.com/api/getDataTable";

                // Send an HTTP GET request to the API
                HttpResponseMessage response = await httpClient.GetAsync(apiUrl);

                // Check if the request was successful
                if (response.IsSuccessStatusCode)
                {
                    // Read the response content as a JSON string
                    string jsonContent=await response.Content.ReadAsStringAsync();

                    // Deserialize the JSON into a DataTable using Newtonsoft.Json
                    DataTable dt = JsonConvert.DeserializeObject(jsonContent);

                    // Now you can work with the dt DataTable
                    foreach (DataRow row in dt.Rows)
                    {
                        foreach (DataColumn col in dt.Columns)
                        {
                            Console.Write(row[col] + "\t");
                        }
                        Console.WriteLine();
                    }
                }
                else
                {
                    Console.WriteLine("Error: " + response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }
        }
    }
}