load grid from a api rest service?

Its possible to load my grid with a rest api instead of directly


11 Replies

DD Dhivyabharathi Dakshinamurthy Syncfusion Team December 28, 2023 03:33 PM UTC

Hi Alexis Gaitan,

Currently we are analyzing the mentioned scenario, we need time to validate and will provide an update on or before January 02, 2024.


Regards,
DhivyaBharathi Dakshinamurthy



SB Sweatha Bharathi Syncfusion Team January 2, 2024 02:47 PM UTC

Hi Alexis Gaitan,


Currently we are analyzing the reported scenario, we need time to validate and will provide an update January 04, 2024.





DD Dhivyabharathi Dakshinamurthy Syncfusion Team January 4, 2024 06:45 PM UTC

Hi Alexis Gaitan,

We regret the inconvenience.

Still we are analyzing the reported scenario, we need more time to validate and will provide an update on or before January 08, 2024.


Regards
DhivyaBharathi Dakshinamurthy



AG Alexis Gaitan January 8, 2024 05:11 PM UTC

any news?



DD Dhivyabharathi Dakshinamurthy Syncfusion Team January 8, 2024 06:09 PM UTC

Hi Alexis Gaitan,

Your requirement, "To load the DataGrid from the REST API", can be achieved by fetching the data online and setting the DataSource of the DataGrid after converting it to JSON data. We have prepared the sample and attached for your reference. 

Kindly refer the below code snippets:

public Form1()


{

     InitializeComponent();

     sfDataGrid1.DataSource = GetRESTData("https://ej2services.syncfusion.com/production/web-services/api/Orders");

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "OrderID" });

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "CustomerID" });

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "EmployeeID" });

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "Freight" });

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "ShipCity" });

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "Verified" });


}


private JArray GetRESTData(string uri)


{

     var webRequest = (HttpWebRequest)WebRequest.Create(uri);

     var webResponse = (HttpWebResponse)webRequest.GetResponse();

     var reader = new StreamReader(webResponse.GetResponseStream());

     string data = reader.ReadToEnd();

     return JsonConvert.DeserializeObject<JArray>(data);


}



We hope this helps, please let us know if you have any concerns.


Regards,
DhivyaBharathi Dakshinamurthy




Attachment: SfDataGrid_REST_API_f3add7e6.zip


AG Alexis Gaitan replied to Dhivyabharathi Dakshinamurthy January 13, 2024 07:17 PM UTC

got this with my api


Deserialized JSON type 'Newtonsoft.Json.Linq.JObject' is not compatible with expected type 'Newtonsoft.Json.Linq.JArray'


my ip test: http://45.237.184.122:4000/clientes?limit=10



DD Dhivyabharathi Dakshinamurthy Syncfusion Team January 15, 2024 05:52 PM UTC

Hi Alexis Gaitan,

The exception " Deserialized JSON type 'Newtonsoft.Json.Linq.JObject' is not compatible with expected type 'Newtonsoft.Json.Linq.JArray' " occurs when there is a 
mismatch between the actual structure and the expected structure of the deserialized JSON.


To resolve this issue we recommend to use the JToken instead of JArray, it can represent either JArray or JObject. 

private JToken GetRESTData(string uri)

 {

     var webRequest = (HttpWebRequest)WebRequest.Create(uri);

     var webResponse = (HttpWebResponse)webRequest.GetResponse();

     var reader = new StreamReader(webResponse.GetResponseStream());

     string data = reader.ReadToEnd();

     return JsonConvert.DeserializeObject<JToken>(data);

 }


If the issue still persists, can you please replicate the issue in the sample which we have provided.
 

This will help us provide the  better solution.

Note : The link mentioned in your response did not load on our end.



Regards,

DhivyaBharathi Dakshinamurthy



AG Alexis Gaitan January 16, 2024 01:48 PM UTC

what about using httpclient? is not a new way?



AG Alexis Gaitan replied to Dhivyabharathi Dakshinamurthy January 16, 2024 01:51 PM UTC

i did the change but response is empty


Image_4055_1705413041938


the answer is this:


{
    "clientes": [
        {
            "idclave_nombre": " EZEQUIEL 23-05-12-Y",
            "fecha_creacion": "2016-05-12",
            "hora_creacion": "11:24:00",
            "nombres": "EZEQUIEL",
            "apellidos": "VERGARA",
            "nombre_usual": null,
            "cedula": "8-196-80",
            "fecha_nacimiento": "1938-01-16",
            "sexo": "M",
            "anuncio": "PERIODICO",
            "medio_especifico": "MI DIARIO",
            "repartidor": null,
            "medio_publicitario": null,
            "mediopublicitario_especifico": null,
            "campana_publicitaria": null,
            "ubicacion": "FALLECIDO",
            "fecha_ubicacion": null,
            "hora_ubicacion": null,
            "nivel": "N??",
            "fecha_seguimiento": "2018-02-06",
            "notas": "OFRECER",
            "colaborador_asignado": null,
            "usuario": "itadmin",
            "clavecarta_trabajo": null,
            "apc_problemas": null,
            "analisis_expediente": "EDAD",
            "acreedor": null,
            "promotor": null,
            "fechaentrega_expediente": null,
            "observaciones": null,
            "unidad_negocio": "0",
            "analista": null,
            "coordinador": null,
            "sucursal": null,
            "contacto": null,
            "oficina": null,
            "ps": null,
            "buenas_referencias": "0",
            "sector": "JUBILADO",
            "empresa": null,
            "id": 7,
            "fecha_actualiza": null,
            "subsector": null
        }
    ],
    "code": 200,
    "status": "success",
    "pagination": {
        "totalRows": "57237",
        "totalPages": 57237,
        "pageSize": 1,
        "page": 1
    }
}


DD Dhivyabharathi Dakshinamurthy Syncfusion Team January 17, 2024 06:30 PM UTC

Hi Alexis Gaitan,

Currently we are analyzing the mentioned scenario, we need time to validate and will provide an update on or before January 19, 2024.


Regards,
DhivyaBharathi Dakshinamurthy



DD Dhivyabharathi Dakshinamurthy Syncfusion Team January 19, 2024 04:37 PM UTC

Hi Alexis Gaitan,

We have modified the sample using HttpClient as per your requirement. We have attached the sample for your reference.



Kindly refer the below code snippets.

public static HttpClient httpClient = new HttpClient();

 

public Form1()

 {

     InitializeComponent();

     GetDataAsync();           

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "OrderID" });

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "CustomerID" });

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "EmployeeID" });

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "Freight" });

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "ShipCity" });

     this.sfDataGrid1.Columns.Add(new GridTextColumn() { MappingName = "Verified" });

 }

 

 public async Task<bool> DownloadJsonAsync()

 {

     try

     {

         var url = https://ej2services.syncfusion.com/production/web-services/api/Orders; //Set your REST API url here

 

         //Sends a request to retrieve data from the web service for the specified Uri

         var response = await httpClient.GetAsync(url);

         using (var stream = await response.Content.ReadAsStreamAsync()) //Reads data as stream

         {

             //Gets the path to the specified folder

             var localFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);

 

             var newpath = Path.Combine(localFolder, "Data.json"); // Combine path with the file name

 

             var fileInfo = new FileInfo(newpath);

             File.WriteAllText(newpath, String.Empty);

 

             //Creates a write-only file stream

             using (var fileStream = fileInfo.OpenWrite())

             {

                 await stream.CopyToAsync(fileStream); //Reads data from the current stream and write to destination stream (fileStream)

             }

         }

     }

     catch (OperationCanceledException e)

     {

         System.Diagnostics.Debug.WriteLine(@"ERROR {0}", e.Message);

         return false;

     }

     catch (Exception e)

     {

         System.Diagnostics.Debug.WriteLine(@"ERROR {0}", e.Message);

         return false;

     }

     return true;

 }

 

 private async void GetDataAsync()

 {

     await DownloadJsonAsync();

     var localFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);

     var fileText = File.ReadAllText(Path.Combine(localFolder, "Data.json"));

     sfDataGrid1.DataSource = JsonConvert.DeserializeObject<JToken>(fileText);           

 }

 


Regards,
DhivyaBharathi Dakshinamurthy


Attachment: SfDataGrid_REST_API_Modified_ab94e55d.zip

Loader.
Up arrow icon