c#中把需要查询的数据名称提前封装成类,然后通过查询数据库,得到多条结果,我想把得到的结果转化为json字符串。
data=[{
"address": "",
"birthday": "1990-05-17",
"education": "",
"groupId": "",
"groupName": "木工班",
"hyzk": "",
"id": "792"
},{
"address": "",
"birthday": "1993-05-17",
"education": "",
"groupId": "",
"groupName": "土建班",
"hyzk": "",
"id": "793"
}......]
应该怎么写???
可以先查询数据库把数据存到DataTable中,然后把DataTable转化为json,下面提供DataTable转化为json方法参考
public string DataTableToJsonWithJavaScriptSerializer(DataTable table)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List < Dictionary < string, object >> parentRow = new List < Dictionary < string, object >> ();
Dictionary < string, object > childRow;
foreach(DataRow row in table.Rows)
{
childRow = new Dictionary < string, object > ();
foreach(DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
封装类是指新建一个包含各项数据的类然后用查询初始化它,还是直接用查询数据构造json?
前者做不到,而且没必要,你只要知道数据库查询结果每一列对应的名称,就能生成json。
百度json encode decode,方法多得是。
你是要将list转换成json?,下面是将List与Table 件的数据转换,文本转换成json是一样的,你看一下下面的代码:
下面的是我转载的CSDN的前辈的,将datatable转换为json
#region 将DataTable数据转换成JSON数据(可用于绑定下拉框)
/// <summary>
/// 将datatable数据转换成JSON数据
/// </summary>
/// <param name="dt">数据集</param>
/// <param name="displayCount">是否显示计数</param>
/// <param name="totalcount">总计数</param>
/// <returns></returns>
public static string DataTableToJson(System.Data.DataTable dt)
{
StringBuilder Json = new StringBuilder();
Json.Append("[");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
string value = dt.Rows[i][j] != null ? dt.Rows[i][j].ToString() : "";
value = HK.Common.Utils.DropHTML(value);
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":\"" + value + "\"");
if (j < dt.Columns.Count - 1)
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - 1)
{
Json.Append(",");
}
}
}
Json.Append("]");
return Json.ToString().Replace("\n", "").Replace("\r", "");
}
#endregion