使用.net處理json陣列,將json陣列轉換為datatable
阿新 • • 發佈:2019-02-01
建立一個實體類:namespace aa.kuai_Model{public class kuai
{ public string id{get;set;} public string name{get;set;} public string order{get;set;} public string num{get;set;} public string updateTime{get;set;} public string message{get;set;} public string errCode{get;set;} public string status{get;set;} public List<ShippmentRecord> data{ get; set; } } public class ShippmentRecord
{ public string time { get; set; }
public string content { get; set; } }}在該cs檔案中新增名稱空間:using System.Web.Script.Serialization;並將該物件例項化:protected static JavaScriptSerializer serializer = new JavaScriptSerializer();.cs檔案中:string json='{"id":"shunfeng","name":"順豐快遞","order":"*********","num":4,"updateTime":"2014-03-28 13:36:17","message":"","errCode":0,"status":4,"data":[{"time":"2014-03-08 21:58:00","content":"已收件"},{"time":"2014-03-08 22:38:35","content":"快件在 深圳 ,準備送往下一站 深圳集散中心 "},{"time":"2014-03-09 00:41:13","content":"快件在 深圳集散中心 ,準備送往下一站 廣州集散中心 "},{"time":"2014-03-09 02:25:20","content":"快件到達廣州集散中心"},{"time":"2014-03-09 04:08:19","content":"快件在 廣州集散中心 ,準備送往下一站 廣州集散中心 "},{"time":"2014-03-09 06:06:45","content":"快件在 廣州集散中心 ,準備送往下一站 廣州 "},{"time":"2014-03-09 08:24:49","content":"正在派件..(派件人:**,電話:***********)"},{"time":"2014-03-09 08:59:44","content":"由於客戶休息,待工作日再次派送"},{"time":"2014-03-10 07:58:19","content":"正在派件..(派件人:**,電話:****)"},{"time":"2014-03-10 09:27:00","content":"簽收人是:*"},{"time":"2014-03-10 09:27:40","content":"派件已簽收"}]}';aa.kuai_Model.kuai shippment = serializer.Deserialize<aa.kuai_Model.kuai>(json);DataTable dtApi = ToDataTableTow(shippment.data);/// <summary> /// 將陣列轉化為datatable /// </summary> /// <param name="list"></param> /// <returns></returns> public static DataTable ToDataTableTow(IList list) { DataTable result = new DataTable(); if (list.Count > 0) { PropertyInfo[] propertys = list[0].GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { result.Columns.Add(pi.Name, pi.PropertyType); } for (int i = 0; i < list.Count; i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in propertys) { object obj = pi.GetValue(list[i], null); tempList.Add(obj); } object[] array = tempList.ToArray(); result.LoadDataRow(array, true); } } return result; }