Search code examples
c#windowsrestsharpelixir-jason

How to read Json responce in to DataGridView using RestSharp in C# windows Application


{
  "success": 1,
  "items": [
    {
      "ItemID": "13",
      "ItemName": "Diamond (50 Kg PP)",
      "ItemDesc": "",
      "MRP": "0",
      "Rate": "0",
      "Unit": "",
      "Weight": "50",
      "ItemGroup": ""
    },
    {
      "ItemID": "8",
      "ItemName": "Extra Milk (59 Kg Jute)",
      "ItemDesc": "",
      "MRP": "0",
      "Rate": "0",
      "Unit": "",
      "Weight": "59",
      "ItemGroup": ""
    },
    {
      "ItemID": "19",
      "ItemName": "Extra Milk (59 Kg PP)",
      "ItemDesc": "",
      "MRP": "0",
      "Rate": "0",
      "Unit": "",
      "Weight": "59",
      "ItemGroup": ""
    },
    {
      "ItemID": "23",
      "ItemName": "Test222",
      "ItemDesc": "",
      "MRP": "0",
      "Rate": "0",
      "Unit": "",
      "Weight": "50",
      "ItemGroup": ""
    }
  ]
}

my code

public  async void myweb()
{
    string vJ = "";
    string url = "https://crmscf.vidyasystems.com/api/gen/items.php";
    var client = new RestClient(url);
    var request = new RestRequest();
           
    var responce = client.Get(request);
    // Console.WriteLine(responce.Content.ToString());
    // txtJson.Text = responce.Content.ToString();             

    vJ =  responce.Content.ToString();
    DataTable dataTable = (DataTable)JsonConvert.DeserializeObject(@vJ, (typeof(DataTable)));
    dgvXml.DataSource = dataTable;
}

I am getting error :

Newtonsoft.Json.JsonSerializationException: 'Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.'


Solution

  • The following uses a different method to read json. The models and helper class belong in their own files.

    enter image description here

    enter image description here

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Net;
    using System.Windows.Forms;
    using Newtonsoft.Json;
    
    namespace DemoApp
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void ReadJsonButton_Click(object sender, EventArgs e)
            {
                try
                {
                    using (var wc = new WebClient())
                    {
                        var json = wc.DownloadString("https://crmscf.vidyasystems.com/api/gen/items.php");
                        Container container = JsonConvert.DeserializeObject<Container>(json);
                        if (container != null && container.success == 1)
                        {
                            var dt = container.items.ToList().ToDataTable();
                        }
                        else
                        {
                            // deal with it
                        }
                    }
                }
                catch (Exception ex)
                {
                    // deal with error
                }
    
            }
        }
    
    
        public class Container
        {
            public int success { get; set; }
            public Item[] items { get; set; }
        }
    
        public class Item
        {
            public string ItemID { get; set; }
            public string ItemName { get; set; }
            public string ItemDesc { get; set; }
            public string MRP { get; set; }
            public string Rate { get; set; }
            public string Unit { get; set; }
            public string Weight { get; set; }
            public string ItemGroup { get; set; }
        }
    
        public static class Operations
        {
            public static DataTable ToDataTable<T>(this IList<T> list) 
                => (DataTable)JsonConvert
                    .DeserializeObject(JsonConvert.SerializeObject(list), (typeof(DataTable)));
        }
    
    }