Man*_*inh 13 c# asp.net json asmx javascriptserializer
我有以下方法:
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 ;
}
Run Code Online (Sandbox Code Playgroud)
在这里我设置ResponseFormat属性是json仍然作为XML返回.
我想用json格式使用这个asmx服务有什么想法吗?
Sar*_*nya 47
我遇到了同样的问题,并包含以下代码以使其工作.
[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";
}
Run Code Online (Sandbox Code Playgroud)
更新:
要获得纯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;
}
Run Code Online (Sandbox Code Playgroud)
但是,这适用于复杂类型,但字符串不会显示任何差异.
| 归档时间: |
|
| 查看次数: |
46715 次 |
| 最近记录: |