Thursday, May 23, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  27] [ 7]  / answers: 1 / hits: 57286  / 11 Years ago, thu, october 24, 2013, 12:00:00

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?


More From » c#

 Answers
4

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.


[#74767] Wednesday, October 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhettforrestm

Total Points: 468
Total Questions: 106
Total Answers: 88

Location: Finland
Member since Sat, Nov 6, 2021
3 Years ago
;