简体   繁体   English

Asp.net 3.5和JSON中的Web服务

[英]Web Service in Asp.net 3.5 and JSON

I have a Web Service in ASP.Net 3.5 and I can not properly generate a JSON. 我在ASP.Net 3.5中有一个Web服务,但无法正确生成JSON。 The formatting is correct, but still does not work when trying to access $. 格式正确,但是在尝试访问$时仍然无法使用。 Ajax. 阿贾克斯 My suspicion is that the header remains as xml and I'm not understanding why. 我怀疑标题仍然是xml,但我不明白为什么。 The following code: 如下代码:

WEB SERVICE: 网络服务:

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data
Imports System.IO
Imports System.Runtime.Serialization.Json

<System.Runtime.Serialization.DataContractAttribute()> _
Public Class Estado

    Dim _ID As Integer = 0
    <System.Runtime.Serialization.DataMemberAttribute()> _
    Public Property ID() As Integer
        Get
            Return _ID
        End Get
        Set(value As Integer)
            _ID = value
        End Set
    End Property

    Dim _Descricao As String = ""
    <System.Runtime.Serialization.DataMemberAttribute()> _
    Public Property Descricao() As String
        Get
            Return _Descricao
        End Get
        Set(value As String)
            _Descricao = value
        End Set
    End Property

    Dim _UF As String
    <System.Runtime.Serialization.DataMemberAttribute()> _
    Public Property UF() As String
        Get
            Return _UF
        End Get
        Set(value As String)
            _UF = value
        End Set
    End Property

End Class

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld() As String
        Return "Hello World"
    End Function

    <WebMethod()> _
    <Script.Services.ScriptMethod(ResponseFormat:=System.Web.Script.Services.ResponseFormat.Json)> _
    Public Function getStates() As String
        Try
            Dim ds As New System.Data.DataSet

            Dim strConexao As String = ""
            strConexao = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString

            Dim conexao As System.Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection()
            conexao.ConnectionString = strConexao
            conexao.Open()

            Dim cmd As System.Data.SqlClient.SqlCommand = New Data.SqlClient.SqlCommand
            cmd.CommandText = "Select ID, Descricao, UF From dbo.States"
            cmd.CommandTimeout = 120
            cmd.Connection = conexao

            Dim adp As System.Data.SqlClient.SqlDataAdapter = New Data.SqlClient.SqlDataAdapter()
            adp.SelectCommand = cmd
            adp.Fill(ds)

            Dim obj As List(Of Estado) = New List(Of Estado)
            For Each dr As DataRow In ds.Tables(0).Rows
                Dim e As Estado = New Estado()
                e.ID = dr.Item("ID")
                e.Descricao = dr.Item("Descricao")
                e.UF = dr.Item("UF")

                obj.Add(e)
            Next

            Dim strRetorno As String = getJSON(obj)


            Return strRetorno
        Catch ex As Exception
            Return "Deu Merda: " + ex.Message
        End Try

    End Function

    Private Function getJSON(obj As Object) As String
        'yourobject is your actual object you want to serialize to json
        Dim serializer As DataContractJsonSerializer = New DataContractJsonSerializer(obj.GetType())

        'create a memory stream
        Dim ms As MemoryStream = New MemoryStream()

        'serialize the object to memory stream
        serializer.WriteObject(ms, obj)

        'convert the serizlized object to string
        Dim jsonString As String = Encoding.Default.GetString(ms.ToArray())

        'close the memory stream
        ms.Close()

        Return jsonString
    End Function
End Class

Web Page: 网页:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WS_JSON_Teste._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>

<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.22/themes/base/jquery-ui.css" type="text/css" media="all" />
<link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.8.22/jquery-ui.min.js" type="text/javascript"></script>

<script type="text/javascript">
    $(document).ready(function ($) {
        $.ajax({
            type: "POST",
            url: "http://localhost:27916/WS_JSON/Service.asmx/getStates",
            contentType: "application/jsonp; charset=utf-8",
            dataType: "jsonp",
            success: function (data) {
                alert("success!");
            },
            failure: function (error) {
                alert("failure!");
            }
        });
    });

</script>

I used this link as a reference. 我使用此链接作为参考。

First off... ASMX is current technology that works just fine. 首先,... ASMX是目前运行良好的技术。 ALWAYS ignore people who say "that's old so it won't work" 总是无视那些说“那是旧的,所以它不起作用”的人

Secondly, you're doing the serialization yourself and that's what is causing the problem. 其次,您要自己进行序列化,这就是导致问题的原因。 You don't have to do that. 您不必这样做。 If your request is done properly, and the service knows you want JSON, all you have to do is return the object, and it will convert it to JSON for you. 如果您的请求正确完成,并且服务知道您想要JSON,那么您要做的就是返回对象,它将为您将其转换为JSON。

See this post: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/ 看到这篇文章: http : //encosia.com/asp-net-web-services-mistake-manual-json-serialization/

Your web service basically can end up looking like this: 您的Web服务基本上可以看起来像这样:

Public Function getStates() as List(Of Estado)
  Dim myStates as List(Of Estado)

  //do the SQL to create the List object - same as above
  //then just do this!
  return myStates
End

That will be much easier! 那会容易得多!

Let me know if there's something you don't understand after reading the article. 阅读本文后,让我知道您是否不了解某些内容。 I'm happy to add more details if it will help. 如果有帮助,我很乐意添加更多详细信息。 I have services running this way right now, so I know they work, and they aren't obsolete. 我现在有以这种方式运行的服务,因此我知道它们可以正常工作,并且它们不会过时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM