我有以下方法:
using System.Web.Services; using System.Web.Script.Services; using System.Web.Script.Serialization; using Newtonsoft.Json; using System.Collections; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] //[System.ComponentModel.ToolboxItem(false)] [System.Web.Script.Services.ScriptService] // [System.Web.Script.Services.ScriptService] public class Tripadvisor : System.Web.Services.WebService { public Tripadvisor () { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string HotelAvailability(string api) { JavaScriptSerializer js = new JavaScriptSerializer(); string json = js.Serialize(api); //JsonConvert.SerializeObject(api); return json ; }
在这里,我将ResponseFormat属性设置为json,但仍将其作为XML返回。
我想使用此asmx服务进行json格式化有什么想法吗?
我遇到了同样的问题,并包含以下代码以使其正常工作。
[WebMethod] [ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)] public void HelloWorld() { Context.Response.Clear(); Context.Response.ContentType = "application/json"; Context.Response.Write("Hello World"); //return "Hello World"; }
更新:
要获得纯json格式,您可以使用如下的javascript序列化程序。
public class WebService1 : System.Web.Services.WebService { [WebMethod] [ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)] public void HelloWorld() { JavaScriptSerializer js = new JavaScriptSerializer(); Context.Response.Clear(); Context.Response.ContentType = "application/json"; HelloWorldData data = new HelloWorldData(); data.Message = "HelloWorld"; Context.Response.Write(js.Serialize(data)); } } public class HelloWorldData { public String Message; }
但是,这适用于复杂类型,但字符串没有任何区别。