【问题标题】:Having strange {"d":null} in JSON response在 JSON 响应中有奇怪的 {"d":null}
【发布时间】:2019-06-01 00:06:07
【问题描述】:

请按如下方式对 Web API 进行 AJAX 调用

$.ajax({
         type: "POST",
         url: "CustomerService.asmx/GetAccounts",
         data: '{"custid":"' + cusID + '"}',
         contentType: "application/json; charset-utf-8",
         dataType: "json",
         success: function (data) {
             datatableVariable = $('#dtAccounts').DataTable({.......

这是我的 ASP.NET Web 方法

<WebMethod()>
Public Sub GetAccounts(ByVal custid As Integer)


    Dim sql As String = "Select * from Accounts WHERE CustomerID =" & custid & " Order by ID"

    Dim constr As String = ConfigurationManager.ConnectionStrings("flashCon").ConnectionString
    Dim accs = New List(Of Accounts)()
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(sql)
            cmd.CommandType = CommandType.Text
            cmd.Connection = con
            con.Open()
            Dim dr = cmd.ExecuteReader()
            If dr.HasRows Then
                While dr.Read
                    Dim acc = New Accounts() With {
                   .custID = Convert.ToInt32(dr("CustomerID").ToString()),
                    .AccNum = dr("AccountNumber").ToString(),
                    .Descri = dr("Description").ToString(),
                    .CurrBalance = dr("CurrentBalance").ToString(),
                    .typOA = dr("TypeOfAccount").ToString(),
                    .Frozen = dr("Frozen").ToString()
                    }
                    accs.Add(acc)
                End While
            End If
        End Using
    End Using
    Dim js = New JavaScriptSerializer()
    Dim strResponse As String = js.Serialize(accs)
    Context.Response.Write(strResponse)
End Sub

返回的 JSON 字符串响应如下所示,带有额外的奇怪 {"d":null} 值,我不知道它来自哪里

[{"custID":2,"AccNum":"KODSW00002","Descri":"","CurrBalance":0,"Frozen":false,"typOA":0}]{"d":null}

如果我使用Context.Response.Flush(),它会消失,然后我从浏览器Server cannot clear headers after HTTP headers have been sent. 收到另一个错误

请有人帮我解决这个问题,已经这样做了好几个星期了

非常感谢

【问题讨论】:

  • 不要使用 JavascriptSerializer。它已被弃用。甚至微软也使用 Json.NET
  • 我想知道你是否解决了这个问题。我在 ajax 调用的最后 json 响应中添加了相同的 {"d":null}。请告诉我 。谢谢。

标签: asp.net json


【解决方案1】:

JavascriptSerializer 已弃用。它是在大多数事实上的 JSON 标准之前创建的,当然在任何实际标准之前。例如,它不使用事实上的 ISO8601 日期格式。

微软的own documentation在最上面说:

Json.NET 应该使用序列化和反序列化。为支持 AJAX 的应用程序提供序列化和反序列化功能。

微软自己在 ASP.NET MVC Web API 中使用 Json.NET。

使用Json.NET ,您可以使用 JsonConvert.Serialize 从对象列表中生成 Json 字符串:

Dim strResponse As String = JsonConvert.Serialize(accs)

【讨论】:

    【解决方案2】:

    在使用Context.Response.Clear()在服务器端给出响应之前,我们必须从 ASP.NET Webservice 中清除默认响应 {d:null} 并设置contentType

    Context.Response.Clear()
    Context.Response.ContentType = "application/json"
    Context.Response.AddHeader("content-length", stringJSON.Length.ToString())
    Context.Response.Flush()
    Context.Response.Write(stringJSON)
    HttpContext.Current.ApplicationInstance.CompleteRequest()
    

    【讨论】:

      【解决方案3】:

      试试这个

      $.ajax({
           type: "POST",
           url: "CustomerService.asmx/GetAccounts",
           data: {custid: cusID},
           dataType: "json",
           success: function (data) {
               alert(data.d); // Should correctly get the response in the d variable.
      

      秘诀在于 JavaScriptSerializer 不需要 contentType: "应用程序/json; charset-utf-8",

      并且在数据中直接写入不带撇号或双引号的参数

      更多信息在:https://www.youtube.com/watch?v=Zq_aMDFeCCA

      问候

      【讨论】:

        【解决方案4】:

        您得到 {"d":null} 因为您的 WebMethod 没有返回值,您只是在写入 Response 对象。

        你应该从你的方法中返回一个字符串:

        Public Sub GetAccounts(ByVal custid As Integer) As String
        
        Dim sql As String = "Select * from Accounts WHERE CustomerID =" & custid & " Order by ID"
        
        Dim constr As String = ConfigurationManager.ConnectionStrings("flashCon").ConnectionString
        Dim accs = New List(Of Accounts)()
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand(sql)
                cmd.CommandType = CommandType.Text
                cmd.Connection = con
                con.Open()
                Dim dr = cmd.ExecuteReader()
                If dr.HasRows Then
                    While dr.Read
                        Dim acc = New Accounts() With {
                       .custID = Convert.ToInt32(dr("CustomerID").ToString()),
                        .AccNum = dr("AccountNumber").ToString(),
                        .Descri = dr("Description").ToString(),
                        .CurrBalance = dr("CurrentBalance").ToString(),
                        .typOA = dr("TypeOfAccount").ToString(),
                        .Frozen = dr("Frozen").ToString()
                        }
                        accs.Add(acc)
                    End While
                End If
            End Using
        End Using
        Dim js = New JavaScriptSerializer()
        Dim strResponse As String = js.Serialize(accs)
        
        <strike>Context.Response.Write(strResponse)</strike>
        

        替换为:

        Return strResponse
        
        End Sub
        

        然后返回的对象将是 {"d": "[{"custID":2,"AccNum":"KODSW00002","Descri":"","CurrBalance":0,"Frozen":false ,"typOA":0}]"},可以通过 javascript 中的 response.d 访问。

        $.ajax({
                 type: "POST",
                 url: "CustomerService.asmx/GetAccounts",
                 data: '{"custid":"' + cusID + '"}',
                 contentType: "application/json; charset-utf-8",
                 dataType: "json",
                 success: function (data) {
                     alert(data.d); // Should correctly get the response in the d variable.
        

        https://stackoverflow.com/a/20471116/4008833

        【讨论】:

        • 方法返回一个字符串给浏览器。这就是Response.Write 所做的。您可能会将其与 ASP.NET MVC 混淆,尽管 Response.Write 也可以在那里工作
        猜你喜欢
        • 2011-09-30
        • 1970-01-01
        • 2018-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多