0

I am hitting api endpoint that returns a json string. I need to take that json string and populate a C# DATATABLE. How is this achieved?

This is the code I have to get the JSON...

[HttpGet]
public IActionResult DTL()
{
    var data = _context.TC.FromSqlRaw("Select * from employeeInfo order by employeeID Asc").ToList();

    //I need data converted to a DataTable C#
}

How do this happen with C# code?

EDIT

This is what my JSON data returned looks like:

{"data":[{"empName": "Jason", "empManager": "Richard", "userID": "ja123"}]}
HotTomales
  • 544
  • 2
  • 6
  • 13

1 Answers1

1

First install NewtonSoft json from Nuget package manager

Then add this in your Namespace

using Newtonsoft.Json;
var dt = JsonConvert.DeserializeObject<System.Data.DataSet>(data.ToString());

EDIT:

Identifier data was of type object, converted it to String and was sorted

Clint
  • 6,011
  • 1
  • 21
  • 28
  • I get build errors of - Argument 1 can not convert from System.Data.DataTable to string, Argument 2 can not convert from System.Type to Newtonsoft.Json.JsonSerializerSettings – HotTomales Dec 20 '19 at 16:55
  • Or you could use `var dt = JsonConvert.DeserializeObject(json);` – stuartd Dec 20 '19 at 16:57
  • @HotTomales, thats because the json should be of type object or you can use Generic as suggested by stuartd – Clint Dec 20 '19 at 17:02
  • @stuartd - I get an error of can not convert from Generic.List to string – HotTomales Dec 20 '19 at 17:11
  • @Clint - I have that package installed and I copied your syntax – HotTomales Dec 20 '19 at 17:12
  • @stuartd: Is your json string a collection ? if yes, then use `var dt =JsonConvert.DeserializeObject>(json);` – Clint Dec 20 '19 at 17:13
  • @Clint - it is a json string. if I try the above syntax I get the same error can not convert from Generic.List to string – HotTomales Dec 20 '19 at 17:15
  • @HotTomales: In your code what type is `var data` and can you share sample value that it holds – Clint Dec 20 '19 at 17:18
  • @Clint - I posted a sample of what the data I am expecting to convert to datatable looks like. --- see my edit – HotTomales Dec 20 '19 at 17:18
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/204621/discussion-between-clint-and-hottomales). – Clint Dec 20 '19 at 17:19