運行到 這行 ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(strJson); 結果 arrayList.Count =0 了 請問應該如何修改,輸入Json為 JsStr = "{ \"code\":\"1001\",\"Id\":\"81\",\"Name\":\"測驗公司\"}"; //Json 字串
函式代碼如下
public static DataTable JsonToDataTable4(string strJson)
{
DataTable dataTable = new DataTable(); //實體化
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大數值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(strJson);
if (arrayList.Count > 0)
{
//表頭
int maxColCount = GetArrayListMaxKeysCount(arrayList);//獲取最多欄位數的行
foreach (Dictionary<string, object> dictionary in arrayList)
{
if (dictionary.Keys.Count<string>() == 0)
{
result = dataTable;
return result;
}
//獲取最大的Keys 欄位集合作為表頭,避免行欄位欄位不一致
if (dataTable.Columns.Count == 0 && dictionary.Keys.Count<string>() == maxColCount)
{
foreach (string current in dictionary.Keys)
{
if (dictionary[current] != null)
{
if (dictionary[current].GetType() == typeof(int))//避免數字丟失,若是int資料轉成decimal
{
dataTable.Columns.Add(current, typeof(decimal));
}
else
{
dataTable.Columns.Add(current, dictionary[current].GetType());
}
}
else//當資料為null時,默認為字串格式
{
dataTable.Columns.Add(current, typeof(string));
}
}
break;
}
}
//為表賦值賦值
foreach (Dictionary<string, object> dictionary in arrayList)
{
DataRow dataRow = dataTable.NewRow();
foreach (string current in dictionary.Keys)
{
if (dictionary[current] != null)
dataRow[current] = dictionary[current];
}
dataTable.Rows.Add(dataRow); //回圈添加行到DataTable中
dataTable.AcceptChanges();
}
}
}
catch
{
throw;
}
result = dataTable;
return result;
}
public static int GetArrayListMaxKeysCount(ArrayList sampleList)
{
try
{
int MaxKeysCout = 0;
foreach (Dictionary<string, object> dictionary in sampleList)
{
int temp = dictionary.Keys.Count<string>();
if (temp > MaxKeysCout)
{
MaxKeysCout = temp;
}
}
return MaxKeysCout;
}
catch (Exception ex)
{
throw ex;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/277256.html
標籤:C#
