I am trying to convert json that I deserialized to a class to a datatable by using the code below ,however the code below fails at the last line.
using (var
Have you tried having your class inherit from the DataTable class? Ideally you would be able to manipulate the data and have the end result still be a DataTable.
For your json string to get deserialized into a DataTable, it needs to be an array of json objects, where each first-level object in the array corresponds to a row. For instance, this would work fine:
string data = "[{\"FirstName\": \"John\", \"LastName\": \"Smith\"}, {\"FirstName\": \"Mohammed\", \"LastName\": \"Lee\"}]";
var dt = JsonConvert.DeserializeObject<DataTable>(data);
Notice that that whole json string is within a []
. It wont work even if it is a json object containing only an array.
If you want to deserialize into a custom type first, then I would suggest that you deserialize the exact same json into a List<T>
instead of a DataTable.
class Name
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
...
var names = JsonConvert.DeserializeObject<List<Name>>(data);
And then there are ways to convert the list to a DataTable. Having said that, once you have deserialized into a custom list type, would you still want to convert that into a DataTable? If the DataTable is to be used for data binding on controls, there are other options for binding sources.
If you have only one object serialized then add the square brackets to be parsed to data table correctly.
var json = JsonConvert.SerializeObject(zone, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
json = "[" + json + "]";
DataTable table = JsonConvert.DeserializeObject<DataTable>(json);