Convert deserialized json class to datatable

2020-03-31 10:34发布

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 webClient = new System.Net.WebClient())
{
    var downloadTable = webClient.DownloadString(url);
    var myTable = JsonConvert.DeserializeObject<leagueTable>(downloadTable);
    DataTable dt = myTable;
}

I know that I could deserialized directly to a datatable but I want to deserialized it to a class first so that I can manipulate the data and let the structure of the data be known to others that use the code.

The JSON is nested and the classes made for it is below

public class leagueTable
{
    public string leaguename { get; set; }
    public int gameday { get; set; }
    public System.Collections.ObjectModel.Collection<Ranking> ranking { get; set; }
}

public class Ranking
{
    public int rank { get; set; }
    public string club { get; set; }
    public int games { get; set; }
    public int points { get; set; }
}

2条回答
甜甜的少女心
2楼-- · 2020-03-31 10:58

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.

查看更多
3楼-- · 2020-03-31 11:03

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.

查看更多
登录 后发表回答