1. 程式人生 > >將json字符串轉換為DataTable

將json字符串轉換為DataTable

實例 for keys col lis 最大數 ict columns value

字符串

{

"Answer": [{
"PatientId": "xx",
"Question": "158",
"AnswerContent": "3"
}, {
"PatientId": "aa",
"Question": "159",
"AnswerContent": "2"
}]

}

public DataTable JsonTdb(string strJson)
{
DataTable dataTable = new DataTable(); //實例化
DataTable result;
try
{

JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); //引用System.Web.Extensions
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大數值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(strJson);
if (arrayList.Count > 0)
{
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == 0)
{
result = dataTable;
// return result;
}
if (dataTable.Columns.Count == 0)
{
foreach (string current in dictionary.Keys)
{
dataTable.Columns.Add(current, dictionary[current].GetType());
}
}
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
dataRow[current] = dictionary[current];
}

dataTable.Rows.Add(dataRow); //循環添加行到DataTable中
}
}
}
catch
{
}
return dataTable;
// return result;
}

將json字符串轉換為DataTable