C#Jarry转datatable
时间: 2023-08-29 12:09:24 浏览: 140
如果你的数据结构是一个简单的`JArray`,可以使用以下代码将其转换为`DataTable`:
```csharp
using Newtonsoft.Json.Linq;
public static DataTable ConvertJArrayToDataTable(JArray jArray)
{
DataTable dataTable = new DataTable();
if (jArray != null && jArray.Count > 0)
{
// 添加列
foreach (JObject jObject in jArray)
{
foreach (JProperty property in jObject.Properties())
{
if (!dataTable.Columns.Contains(property.Name))
{
dataTable.Columns.Add(property.Name, typeof(object));
}
}
}
// 添加行
foreach (JObject jObject in jArray)
{
DataRow dataRow = dataTable.NewRow();
foreach (JProperty property in jObject.Properties())
{
dataRow[property.Name] = GetValue(property.Value);
}
dataTable.Rows.Add(dataRow);
}
}
return dataTable;
}
private static object GetValue(JToken jToken)
{
if (jToken.Type == JTokenType.Object || jToken.Type == JTokenType.Array)
{
return jToken.ToString();
}
return ((JValue)jToken).Value;
}
```
使用示例:
```csharp
string json = "[{\"Name\":\"John\",\"Age\":25,\"City\":\"New York\"},{\"Name\":\"Emily\",\"Age\":30,\"City\":\"London\"}]";
JArray jArray = JArray.Parse(json);
DataTable dataTable = ConvertJArrayToDataTable(jArray);
```
这样,你就可以将`JArray`转换为`DataTable`了。请确保在使用之前添加了对`Newtonsoft.Json`包的引用。
阅读全文