将反序列化的 json 类转换为数据表 [英] Convert deserialized json class to datatable

查看:35
本文介绍了将反序列化的 json 类转换为数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用下面的代码将我反序列化为类的 json 转换为数据表,但是下面的代码在最后一行失败.

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.

JSON 是嵌套的,为它制作的类在下面

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; }
}

推荐答案

为了让你的 json 字符串反序列化为 DataTable,它需要是一个 json 对象数组,其中数组中的每个一级对象对应一个排.例如,这可以正常工作:

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);

请注意,整个 json 字符串都在 [] 中.即使它是一个只包含一个数组的 json 对象,它也不会工作.

Notice that that whole json string is within a []. It wont work even if it is a json object containing only an array.

如果您想先反序列化为自定义类型,那么我建议您将完全相同的 json 反序列化为 List 而不是 DataTable.

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);

然后有将列表转换为数据表的方法.话虽如此,一旦您反序列化为自定义列表类型,您还想将其转换为 DataTable 吗?如果 DataTable 用于控件上的数据绑定,则还有其他用于绑定源的选项.

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.

这篇关于将反序列化的 json 类转换为数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆