要用到Newtonsoft.Json.dll
简单了解JArray和JObject
string json = @"[ { id: 1, title: '必订款', no: 'bdk', flag_ka: 'y' }, { id: 2, title: '必订规格', no: 'bdgg', flag_ka: 'n' } ]"; Newtonsoft.Json.Linq.JArray array = Newtonsoft.Json.JsonConvert.DeserializeObject(json) as JArray; for (int i = 0; i < array.Count; i++) { JObject obj = array[i] as JObject; int id = Convert.ToInt32(obj["id"]); var title = obj["title"]; }
Json转DataTable
1 string json = @"[ 2 { id: 1, title: '必订款', no: 'bdk', flag_ka: 'y' }, 3 { id: 2, title: '必订规格', no: 'bdgg', flag_ka: 'n' } 4 ]"; 5 Newtonsoft.Json.Linq.JArray array = Newtonsoft.Json.JsonConvert.DeserializeObject(json) as JArray; 6 StringBuilder columns = new StringBuilder(); 7 DataTable table = new DataTable(); 8 JObject objColumns = array[0] as JObject; 9 //构造表头 10 foreach (JToken jkon in objColumns.AsEnumerable<JToken>()) 11 { 12 string name = ((JProperty)(jkon)).Name; 13 columns.Append(name + ","); 14 table.Columns.Add(name); 15 } 16 //向表中添加数据 17 for (int i = 0; i < array.Count; i++) 18 { 19 DataRow row = table.NewRow(); 20 JObject obj = array[i] as JObject; 21 foreach (JToken jkon in obj.AsEnumerable<JToken>()) 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 }