我正在尝试执行一个Web服务,该服务使用以下代码返回DataTable:
$.ajax({ type: "POST", url: url, data: data, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { //do things } });
如果webservice返回一个类,那么它就可以工作,因此它与输入参数等无关.它只在web方法返回一个数据表时失败(数据表只有2列和2行用于我正在进行的测试).
WebService类使用[ScriptService]属性进行修饰,因此我认为ASP.NET会自动将返回值序列化为JSON.它似乎不适用于数据表.
我发现的唯一解决方案是返回一个字符串(一个手动JSON序列化对象),但这样做对我来说似乎不对.
我正在使用Visual Studio 2008和.Net 3.5
最后,我决定使用JavaScriptSerializer类将DataTable转换为JSON字符串.不幸的是,这个类不适用于DataTable,所以我将DataTable转换为dictionnaries列表并将该列表传递给JavaScriptSerializer类.它只需几行代码就可以正常工作.
VB.net中的示例:
Public Function GetJson(ByVal dt As DataTable) As String Dim serializer As System.Web.Script.Serialization.JavaScriptSerializer = New System.Web.Script.Serialization.JavaScriptSerializer() Dim rows As New List(Of Dictionary(Of String, Object)) Dim row As Dictionary(Of String, Object) For Each dr As DataRow In dt.Rows row = New Dictionary(Of String, Object) For Each col As DataColumn In dt.Columns row.Add(col.ColumnName, dr(col)) Next rows.Add(row) Next Return serializer.Serialize(rows) End Function
最简单的方法是使用LINQ to DataSet扩展.首先需要使用LINQ to DataSet从DataTable创建一个通用列表(在这种情况下,SearchSerialResults只是一个DTO).
var resultItems = (from DataRow dr in _returnedData.AsEnumerable() select new SearchSerialResults { ContractLineItem = (int)dr["fldContractLineItemID"], SearchItem = (string)dr["Search Item"], Customer = (string)dr["Customer"], DeviceFound = (string)dr["Device Found"], Country = (string)dr["Country"], City = (string)dr["City"], ContractNumber = (string)dr["Contract Number"], QuoteNumber = (string)dr["Quote Number"], BeginDate = (string)dr["Begin Date"], EndDate = (string)dr["End Date"] }).ToList();
在这种情况下,_returnedData是DataTable.第2步是进行转换.在这种情况下,我为jqGrid返回一个Json对象.
var jsonObject = new { total = totalPages, pageSize, records = totalRecords, rows = (from SearchSerialResults item in resultItems select new { id = item.ContractLineItem, cell = new[] { item.ContractLineItem.ToString(), item.SearchItem, item.DeviceFound, item.Customer, item.ContractNumber, item.QuoteNumber, item.Country, item.City, item.BeginDate, item.EndDate, "" } }).ToArray() }; return Json(jsonObject) // for MVC