Search code examples
c#jsonjson.net

How to Convert JSON Data to DataTable


I have JSON data as below:

{
"Data":[
    {
        "Customer":"C1",
        "ID":"11111",
        "Desc":"Row 1",
        "Price":"123456"
    },
    {
        "Customer":"C2",
        "ID":"22222",
        "Desc":"Row 2",
        "Price":"789012"
    },
    {
        "Customer":"C3",
        "ID":"33333",
        "Desc":"Row 3",
        "Price":"345678"
    }
],
"Success":true
}

How can I convert this data into a C# DataTable as like as this table

---------------------------------------------
Customer    |  ID       |  Desc    |   Price  
---------------------------------------------
C1          | 11111     | Row 1    |  123456   
C2          | 22222     | Row 2    |  789012   
C3          | 33333     | Row 3    |  345678   

and also read Success value in to a variable

I want to use Success Variable in my code and display the table in a gridview.

I have tried this code but it's not working:

DataTable gdata = JsonConvert.DeserializeObject<DataTable>(result);

Solution

  • Json.NET supports serializing data tables as a array of objects, however the data table in your JSON is nested inside a "Data" property so you need to wrap the DataTable in some root object. An anonymous object should be sufficient:

    var root = JsonConvert.DeserializeAnonymousType(result, new { Data = default(DataTable), Success = default(bool) });
    var gdata = root?.Data;
    var success = root?.Success ?? false;
    

    Alternatively you could introduce a generic root model like so:

    public class DataRoot<T>
    {
        public T Data { get; set; }
        public bool Success { get; set; }
    }
    

    And do:

    var root = JsonConvert.DeserializeObject<DataRoot<DataTable>>(result);
    

    Demo fiddle here.