如何从2.0 asmx Web服务返回JSON

我正在使用.Net framework 2.0 / jQuery对2.0 Web服务进行Ajax调用。无论我在ajax调用中将contentType设置为什么,该服务始终返回XML。我希望它返回Json!


这里是电话:


      $(document).ready(function() {

         $.ajax({

            type: "POST",

            url: "DonationsService.asmx/GetDate",

            data: "{}",

            contentType: "application/json; charset=utf-8",

            dataType: "json",

            success: function(msg) {

              // Hide the fake progress indicator graphic.

              $('#RSSContent').removeClass('loading');


              // Insert the returned HTML into the <div>.

              $('#RSSContent').html(msg.d);

            }

          });

        });    

这是Fiddler中的请求标头的样子:


POST /DonationsService.asmx/GetDate HTTP/1.1

x-requested-with: XMLHttpRequest

Accept-Language: en-us

Referer: http://localhost:1238/text.htm

Accept: application/json, text/javascript, */*

Content-Type: application/json; charset=utf-8

Accept-Encoding: gzip, deflate

User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; eMusic DLM/4; .NET CLR 2.0.50727)

Host: localhost:1238

Content-Length: 2

Connection: Keep-Alive

Pragma: no-cache

我尝试将contentType设置为'text / json'并获得相同的结果。


这是Web服务方法:


<WebMethod()> _

Public Function GetDate() As String


    'just playing around with Newtonsoft.Json

    Dim sb As New StringBuilder

    Dim sw As New IO.StringWriter(sb)

    Dim strOut As String = String.Empty


    Using jw As New JsonTextWriter(sw)

        With jw

            .WriteStartObject()

            .WritePropertyName("DateTime")

            .WriteValue(DateTime.Now.ToString)

            .WriteEndObject()

        End With

        strOut = sw.ToString

    End Using


    Return strOut


End Function

这是它返回的内容:


<?xml version="1.0" encoding="utf-8"?>

<string xmlns="http://DMS.Webservices.org/">{"DateTime":"11/13/2008 6:04:22 PM"}</string>

有人知道我要Json时如何强制Web服务返回Json吗?


请不要告诉我升级到.Net Framework 3.5或类似的东西(我不是那么愚蠢)。我需要一个2.0解决方案。


慕码人8056858
浏览 626回答 3
3回答

慕姐4208626

响应被包装在一个元素中,因为您在方法中说它将返回一个字符串。您可以使用它来发送普通的json,但是您的wsdl将被欺骗(该函数无效,但确实会响应数据)。[WebMethod(Description="return pure JSON")]public void retrieveByIdToPureJSON( int id ){&nbsp; Context.Response.Write( JsonConvert.SerializeObject( mydbtable.getById(id) );}汤姆,祝你好运顺便说一句:请参阅Newtonsoft.Json for JsonConvert
打开App,查看更多内容
随时随地看视频慕课网APP