I have the following method:
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 ;
}
Here i set ResponseFormat attribute is json s still being returned as XML.
I want to json format using this asmx service Any ideas?
For example you can use below code (if you are using jquery) instead of changing somethings in WebService: $. ajax({ type: "POST", url: '/ServiceName. asmx/WebMethodName', date: {}, contentType: "application/json; charset=utf-8", success: function (data) { // Some code; } });
SOAP relies exclusively on XML to provide messaging services, so if you really want/need to return JSON then you would need to wrap it in CDATA in the SOAP XML body. Unlike SOAP, however, REST does not have to use XML to provide the response, therefore you can output the data in other formats such as JSON.
I faced the same issue, and included the below code to get it work.
[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";
}
Update:
To get a pure json format, you can use javascript serializer like below.
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;
}
However this works for complex types, but string does not show any difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With