using System.Web.Script.Serialization;
using System.Collections;
using System.IO;
String line = "";
try
{ // Open the text file using a stream reader.
string filename = AppDomain.CurrentDomain.BaseDirectory;
using (StreamReader sr = new StreamReader(filename + @"\data_json\Antenna_DR_json\q9qwy-nvsns.json"))
{
// Read the stream to a string, and write the string to the console.
line = sr.ReadToEnd();
// Console.WriteLine(line);
}
}
catch (IOException ex)
{
}
DataTable json_data = JsonToDataTable(line);
#region json To datatable
public DataTable JsonToDataTable(string json)
{
DataTable dataTable = new DataTable(); //例項化
DataTable result;
try
{
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
javaScriptSerializer.MaxJsonLength = Int32.MaxValue; //取得最大數值
ArrayList arrayList = javaScriptSerializer.Deserialize<ArrayList>(json);
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
{
}
result = dataTable;
return result;
}
#endregion
沒有留言:
張貼留言