使用 jquery 将数据表转换为 Json [英] DataTable to Json using jquery

查看:23
本文介绍了使用 jquery 将数据表转换为 Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行一个 Web 服务,该服务返回一个带有以下代码的 DataTable:

I'm trying to execute a web service which returns a DataTable with the following piece of code:

$.ajax({  
    type: "POST",  
    url: url,  
    data: data,   
    contentType: "application/json; charset=utf-8",  
    dataType: "json",  
    success: function(msg) {  
        //do things  
        }  
    }); 

如果 webservice 返回一个类,那么它就可以工作,所以它与输入参数等无关.它只会在 web 方法返回数据表时失败(数据表只有 2 列和 2 行,用于我的测试)在做).

If the webservice returns a class then it works so it has nothing to do with the input paramters etc. It only fails when the web method returns a datatable (the datatable only has 2 columns and 2 rows for the test I'm doing).

WebService 类使用 [ScriptService] 属性进行修饰,因此我认为 ASP.NET 会自动将返回值序列化为 JSON.它似乎不适用于数据表.

The WebService class is decorated with the [ScriptService] attribute so I thought that ASP.NET would automatically serialize the return value as JSON. It doesn't seem to work with datatable.

我发现的唯一解决方案是返回一个字符串(一个手动 JSON 序列化的对象),但对我来说这样做似乎不正确.
我正在使用带有 .Net 3.5 的 Visual Studio 2008

The only solution I've found was to return a string (a manually JSON serialized object) but it doesn't seem right to me to do it this way.
I'm using Visual Studio 2008 with .Net 3.5

推荐答案

最后,我决定使用 JavaScriptSerializer 类将 DataTable 转换为 JSON 字符串.不幸的是,这个类不适用于 DataTable,所以我将 DataTable 转换为一个字典列表,并将该列表传递给 JavaScriptSerializer 类.只需几行代码,它就可以正常工作.
VB.net 中的示例:

In the end, I've decided to use the JavaScriptSerializer class to convert the DataTable into a JSON string. Unfortunately, this class doesn't work with a DataTable so I converted the DataTable into a list of dictionnaries and pass that list to the JavaScriptSerializer class. It takes only a few lines of code and it works fine.
Example in 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

这篇关于使用 jquery 将数据表转换为 Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆