【求助】 C#应用JSON转换DataTable 范围空
运行到 这行 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;
}
}