如何从 3.5 asmx Web 服务获取 JSON 响应 [英] How to get JSON response from a 3.5 asmx web service

查看:31
本文介绍了如何从 3.5 asmx Web 服务获取 JSON 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

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 s 仍然作为 XML 返回.

Here i set ResponseFormat attribute is json s still being returned as XML.

我想使用这个 asmx 服务进行 json 格式有什么想法吗?

I want to json format using this asmx service Any ideas?

推荐答案

我遇到了同样的问题,并包含了以下代码以使其正常工作.

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";
}

更新:

要获得纯 json 格式,您可以使用如下所示的 javascript 序列化程序.

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.

这篇关于如何从 3.5 asmx Web 服务获取 JSON 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆