我有以下格式的JSON:
[ {"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} ]
如何将其转换为C#DataTable对象,如下所示?
DataTable
--------------------------------------------------------------------- ID | Name | Add | Edit | View | Authorize --------------------------------------------------------------------- 10 | User | true | true | true | true 11 | Group | true | true | true | true 12 | Permission| true | true | true | true
将您的jsonstring反序列化为某个类
List<User> UserList = JsonConvert.DeserializeObject<List<User>>(jsonString);
将以下扩展方法写入您的项目
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; }
通话额外资讯方法
UserList.ToDataTable<User>();