-1

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);
dbc
  • 104,963
  • 20
  • 228
  • 340
Hadi Barak
  • 480
  • 1
  • 4
  • 17
  • 2
    What have you tried so far? – Abhishek Dec 23 '20 at 21:07
  • 1
    Does this answer your question? [Convert JSON to DataTable](https://stackoverflow.com/questions/11981282/convert-json-to-datatable) – Luuk Dec 23 '20 at 21:09
  • The data table is nested inside a `Data` property so use `JsonConvert.DeserializeAnonymousType(result, new { Data = default(DataTable) })?.Data;`. Do you need an answer still? – dbc Dec 24 '20 at 02:33
  • If you also need `Success` you can do `var root = JsonConvert.DeserializeAnonymousType(result, new { Data = default(DataTable), Success = default(bool) });`. Or define an explicit root data model with `Data` and `Succes` properties. – dbc Dec 24 '20 at 15:53

1 Answers1

1

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.

dbc
  • 104,963
  • 20
  • 228
  • 340