小子参考(抄袭加改造)网上相关资源写了一个类,以实现 将datatable转化为IDictionary
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
namespace AssetInverntoryService
{
public class DataTableConverter : JavaScriptConverter
{
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
DataTable dt = obj as DataTable;
Dictionary<string, object> result = new Dictionary<string, object>();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();//<string,object>
foreach (DataRow dr in dt.Rows)
{
Dictionary<string, object> row = new Dictionary<string, object>();//<string,object>
foreach (DataColumn dc in dt.Columns)
{
if (dc.ColumnName == "Num")
{
row.Add(dc.ColumnName, dr[dc.ColumnName]);
}
else
{
row.Add(dc.ColumnName, dr[dc.ColumnName].ToString());
}
}
rows.Add(row);
}
result["Rows"] = rows;
return result;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
/// <summary>
/// 获取本转换器支持的类型
/// </summary>
public override IEnumerable<Type> SupportedTypes
{
get { return new Type[] { typeof(DataTable) }; }
}
}
}
在webservice中,代码如下,在实际使用时发现序列化为json的类还有改进余地,需要好好想想……
[WebMethod(Description = "xml2Json查询")]
public void JsonTest()
{
DataTable dataTable = new DataTable();
dataTable.TableName = "QueryData";
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
string sql = @"select * FROM [AssetInventory].[dbo].[assetInfors] ";
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
//SqlParameter ID = new SqlParameter("@lot_id", LotID);
//sqlCommand.Parameters.Add(ID);
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
sqlDataAdapter.Fill(dataTable);
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DataTableConverter() });
string strJson = jss.Serialize(dataTable);
//可考虑优化序列化类,以避免再正则取出需要信息
string pattern = @"\[.*]";
string str = "";
foreach (Match match in Regex.Matches(strJson, pattern))
{
str = match.Value;//此处匹配一个 否则 str=str+match.Value;
}
sqlConnection.Close();
sqlCommand.Dispose();
sqlConnection.Dispose();
Context.Response.ContentType = "text/plain;charset=utf-8";//解决乱码代码
Context.Response.Write(str);
Context.Response.End();
}