我需要我的Web服务以返回JSON …
我的.asmx文件中包含以下代码:
namespace Feed { [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] public class searchPerson : System.Web.Services.WebService { [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public Person GetDave() { Person dave = new Person(); dave.FirstName = "Dave"; dave.LastName = "Ward"; return dave; } } }
返回以下内容:
<?xml version="1.0" encoding="utf-8"?> <Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/"> <FirstName>Dave</FirstName> <LastName>Ward</LastName> </Person>
如何强制它返回JSON而不是XML?
您的Web服务定义看起来正确。确保通过帖子调用服务,并记住该键将“内容类型”标头指定为application/json。
application/json
(这是使用jQuery,但如果您愿意,可以使用低级JavaScript)
$.ajax({ type: "POST", contentType: "application/json; charset=utf-8;", url: "http://MyWebServiceURL", data: JSON.stringify({ ParameterName: "DataToSend" }), dataType: "json", success: function (data, textStatus, jqXHR) { //do something }, error: function (jqXHR, textStatus, errorThrown) { //fail nicely } });