为了账号安全,请及时绑定邮箱和手机立即绑定

如何从2.0 asmx Web服务返回JSON

如何从2.0 asmx Web服务返回JSON

慕码人8056858 2019-11-18 13:16:46
我正在使用.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.1x-requested-with: XMLHttpRequestAccept-Language: en-usReferer: http://localhost:1238/text.htmAccept: application/json, text/javascript, */*Content-Type: application/json; charset=utf-8Accept-Encoding: gzip, deflateUser-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:1238Content-Length: 2Connection: Keep-AlivePragma: 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 strOutEnd 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解决方案。
查看完整描述

3 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

响应被包装在一个元素中,因为您在方法中说它将返回一个字符串。您可以使用它来发送普通的json,但是您的wsdl将被欺骗(该函数无效,但确实会响应数据)。


[WebMethod(Description="return pure JSON")]

public void retrieveByIdToPureJSON( int id )

{

  Context.Response.Write( JsonConvert.SerializeObject( mydbtable.getById(id) );

}

汤姆,祝你好运


顺便说一句:请参阅Newtonsoft.Json for JsonConvert


查看完整回答
反对 回复 2019-11-18
  • 3 回答
  • 0 关注
  • 624 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信