JSON转换到数据表 [英] Convert JSON to DataTable

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

问题描述

我在JSON格式如下:

  [
    {ID:10,名:用户,增加:假的,编辑:真实的授权:真的,观:真正},
    {ID:11,名:集团,增加:真实的,编辑:假的,授权:假的,观点:真正},
    {ID:12,名:允许,增加:真实的,编辑:真实的授权:真的,观:真正}
]

我怎么可以转换成C#数据表对象,如下所示?

  -------------------------------------- -------------------------------
ID |名称|添加|编辑|查看|授权
-------------------------------------------------- -------------------
10 |用户|真|真|真|真正
11 |集团|真|真|真|真正
12 |权限|真|真|真|真正


解决方案

反序列化jsonstring一些类

列表<使用者> UserList的= JsonConvert.DeserializeObject<名单<使用者>>(jsonString);

写如下的<一个href=\"http://stackoverflow.com/questions/564366/convert-generic-list-enumerable-to-datatable\">extension方法您的项目

 公共静态数据表ToDataTable&LT; T&GT;(这个IList的&LT; T&GT;数据)
{
    PropertyDescriptorCollection道具=
    TypeDescriptor.GetProperties(typeof运算(T));
    数据表表=新的DataTable();
    的for(int i = 0; I&LT; props.Count;我++)
    {
    PropertyDescriptor的道具=道具[I]
    table.Columns.Add(prop.Name,prop.PropertyType);
    }
    [对象]值=新对象[props.Count]
    的foreach(在数据T项)
    {
    的for(int i = 0; I&LT; values​​.Length;我++)
    {
        值[I] =道具[I] .GetValue(项目);
    }
    table.Rows.Add(值);
    }
    返回表;
}

调用扩展方法,像

UserList.ToDataTable&lt;使用者&GT;();

I have JSON in the following format:

[
    {"id":"10","name":"User","add":false,"edit":true,"authorize":true,"view":true},
    {"id":"11","name":"Group","add":true,"edit":false,"authorize":false,"view":true},
    {"id":"12","name":"Permission","add":true,"edit":true,"authorize":true,"view":true}
]

How can I convert that into a C# DataTable object as follows?

---------------------------------------------------------------------
ID    |  Name     |  Add    |   Edit  | View   | Authorize
---------------------------------------------------------------------
10    | User      | true    |  true   | true   |  true
11    | Group     | true    |  true   | true   |  true
12    | Permission| true    |  true   | true   |  true

解决方案

Deserialize your jsonstring to some class

List<User> UserList = JsonConvert.DeserializeObject<List<User>>(jsonString);

Write following extension method to your project

public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
    TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for(int i = 0 ; i < props.Count ; i++)
    {
    PropertyDescriptor prop = props[i];
    table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
    for (int i = 0; i < values.Length; i++)
    {
        values[i] = props[i].GetValue(item);
    }
    table.Rows.Add(values);
    }
    return table;        
}

Call extension method like

UserList.ToDataTable<User>();

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

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