使用Newtonsoft JsonConvert反序列化Json数据到DataTable

 1 //JsonStr为Json字符串

 2  JArray array = JsonConvert.DeserializeObject(JsonStr) as JArray;//反序列化为数组

 3 if (array.Count > 0)

 4             {

 5                 StringBuilder columns = new StringBuilder();

 6                 DataTable table = new DataTable();

 7                 JObject objColumns = array[0] as JObject;

 8                 //构造表头

 9                 foreach (JToken jkon in objColumns.AsEnumerable<JToken>())

10                 {

11                     string name = ((JProperty)(jkon)).Name;

12                     columns.Append(name + ",");

13                     table.Columns.Add(name);

14                 }

15                 //向表中添加数据

16                 for (int i = 0; i < array.Count; i++)

17                 {

18                     DataRow row = table.NewRow();

19                     JObject obj = array[i] as JObject;

20                     foreach (JToken jkon in obj.AsEnumerable<JToken>())

21                     {

22 

23                         string name = ((JProperty)(jkon)).Name;

24                         string value = ((JProperty)(jkon)).Value.ToString();

25                         row[name] = value;

26                     }

27                     table.Rows.Add(row);

28                 }

29           }

 

你可能感兴趣的:(Datatable)