C# 将 JSON 转换为数据表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11981282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert JSON to DataTable
提问by Nithesh Narayanan
I have JSON in the following format:
我有以下格式的 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}
]
How can I convert that into a C# DataTableobject as follows?
如何将其转换为 C#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
采纳答案by Pravin Pawar
Deserialize your jsonstring to some class
将您的 jsonstring 反序列化为某个类
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>();
回答by danish
回答by Talha
I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...
我建议您使用JSON.NET。它是一个开源库,用于将您的 c# 对象序列化和反序列化为 json 并将 Json 对象序列化和反序列化为 .net 对象......
Serialization Example:
序列化示例:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
回答by Kyle
There is an easier method than the other answers here, which require first deserializing into a c# class, and then turning it into a datatable.
这里有一种比其他答案更简单的方法,它需要首先反序列化为 ac# 类,然后将其转换为数据表。
It is possible to go directly to a datatable, with JSON.NET and code like this:
可以使用 JSON.NET 和如下代码直接访问数据表:
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
回答by Mohammed Ghouse
It can also be achieved using below code.
也可以使用下面的代码来实现。
DataSet data = JsonConvert.DeserializeObject<DataSet>(json);
回答by ne1410s
One doesn't always know the type into which to deserialize. So it would be handy to be able to take any JSON (that contains some array) and dynamically produce a table from that.
人们并不总是知道反序列化的类型。因此,能够采用任何 JSON(包含一些数组)并从中动态生成一个表会很方便。
An issue can arise however, where the deserializer doesn't know where to look for the array to tabulate. When this happens, we get an error message similar to the following:
但是,可能会出现一个问题,其中解串器不知道在哪里查找要制表的数组。发生这种情况时,我们会收到类似于以下内容的错误消息:
Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.
读取 DataTable 时出现意外的 JSON 标记。预期的 StartArray,得到 StartObject。路径 '',第 1 行,位置 1。
Even if we give it come encouragement or prepare our json accordingly, then "object" types within the array can still prevent tabulation from occurring, where the deserializer doesn't know how to represent the objects in terms of rows, etc. In this case, errors similar to the following occur:
即使我们给予它鼓励或相应地准备我们的 json,那么数组中的“对象”类型仍然可以防止发生制表,其中反序列化器不知道如何根据行等表示对象。在这种情况下,出现类似如下错误:
Unexpected JSON token when reading DataTable: StartObject. Path '[0].__metadata', line 3, position 19.
读取数据表时出现意外的 JSON 标记:StartObject。路径 '[0].__metadata',第 3 行,位置 19。
The below example JSON includes both of these problematic features:
下面的示例 JSON 包括这两个有问题的功能:
{
"results":
[
{
"Enabled": true,
"Id": 106,
"Name": "item 1",
},
{
"Enabled": false,
"Id": 107,
"Name": "item 2",
"__metadata": { "Id": 4013 }
}
]
}
So how can we resolve this, and still maintain the flexibility of not knowing the type into which to derialize?
那么我们如何解决这个问题,同时仍然保持不知道要反序列化的类型的灵活性呢?
Well here is a simple approach I came up with (assuming you are happy to ignore the object-type properties, such as __metadata in the above example):
好吧,这是我想出的一个简单方法(假设您很乐意忽略对象类型属性,例如上面示例中的 __metadata):
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Linq;
...
public static DataTable Tabulate(string json)
{
var jsonLinq = JObject.Parse(json);
// Find the first array using Linq
var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
var trgArray = new JArray();
foreach (JObject row in srcArray.Children<JObject>())
{
var cleanRow = new JObject();
foreach (JProperty column in row.Properties())
{
// Only include JValue types
if (column.Value is JValue)
{
cleanRow.Add(column.Name, column.Value);
}
}
trgArray.Add(cleanRow);
}
return JsonConvert.DeserializeObject<DataTable>(trgArray.ToString());
}
I know this could be more "LINQy" and has absolutely zero exception handling, but hopefully the concept is conveyed.
我知道这可能更“LINQy”并且绝对零异常处理,但希望这个概念得到传达。
We're starting to use more and more services at my work that spit back JSON, so freeing ourselves of strongly-typing everything, is my obvious preference because I'm lazy!
我们开始在我的工作中使用越来越多的服务,这些服务会吐出 JSON,因此摆脱对所有内容的强类型化是我的明显偏好,因为我很懒惰!
回答by RajN
Here is another seamless approach to convert JSON to Datatable using Cinchoo ETL- an open source library
这是使用Cinchoo ETL(一个开源库)将 JSON 转换为 Datatable 的另一种无缝方法
Sample below shows how to convert
下面的示例显示了如何转换
string 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}
]";
using (var r = ChoJSONReader.LoadText(json))
{
var dt = r.AsDataTable();
}
Hope it helps.
希望能帮助到你。
回答by Dilip Kumar Choudhary
json = File.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\" +download_file[0]);
DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

