使用.net处理json数组,将json数组转换为datatable

创建一个实体类:
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 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(json);
DataTable dtApi = ToDataTableTow(shippment.data);

///
    /// 将数组转化为datatable
    ///
    ///
    ///
    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;
    }

你可能感兴趣的:(ASP.NET方面)