如何从asp.net中的datatable创建.json文件 [英] How to create .json file from datatable in asp.net
本文介绍了如何从asp.net中的datatable创建.json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,我想阅读一些加载方法()从我的数据库中获取数据并将其存储在.json文件中..我在谷歌中读过几篇文章,但在每篇文章中,他们只创建一个json对象,但在我的情况下,我需要将数据存储在单独的.json文件中..所以请帮助..
Hi everybody, I want to read some load method() to get datas from my DB and store it in .json file.. I have read several articles in google but in every article, they are creating only a json objects, but in my case, I need to store the datas in a separate .json file.. So please help..
推荐答案
Hi Manikandan,
请使用此方法从您的数据创建.json文件...
Hi Manikandan,
Please use this method to create .json file from your datable...
public bool WriteJason(DataTable dt, string path)
{
try
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, string>> rows = new List<Dictionary<string, string>>();
Dictionary<string, string> row = null;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, string>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName.Trim().ToString(), Convert.ToString(dr[col]));
}
rows.Add(row);
}
string jsonstring = serializer.Serialize(rows);
using (var file = new StreamWriter(path, false))
{
file.Write(jsonstring);
file.Close();
file.Dispose();
}
return true;
}
catch { return false; }
}
你可以像这样调用这个函数......
and you can call this function like this...
DataTable dt = new DataTable("Student");
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("RollNo");
for (int i = 0; i < 5; i++)
{
DataRow dr = dt.NewRow();
dr["ID"] = i.ToString();
dr["Name"] = "ABC" + i.ToString();
dr["RollNo"] = "RN" + i.ToString();
dt.Rows.Add(dr);
}
dt.AcceptChanges();
string filePath = @"D:\test.json";
WriteJason(dt, filePath);
这篇关于如何从asp.net中的datatable创建.json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文