如何从一个3.5 ASMX Web服务的JSON响应 [英] How to get JSON response from a 3.5 asmx web service

查看:98
本文介绍了如何从一个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属性仍然被作为XML返回JSON秒。

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

我要JSON formet使用此ASMX服务
任何想法?
谢谢

I want to json formet using this asmx service any Idea? Thanks

推荐答案

我面临着同样的问题,包括以下code得到它的工作。

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天全站免登陆