四时宝库

程序员的知识宝库

webservice返回xml转json(webservice返回多个参数)

现在使用webservice开发的项目仍然比较多,但由于json的广泛使用,虽然项目采用webservice,但是实际上很多的返回值格式已经是json。但是webservice最终的返回结果却仍然是xml格式的,而无法再客户端直接获取到json格式。接下来就以.net为例说明一下如何将xml返回的json提取出来,直接在客户端以json格式直接使用。

如WebService有以下方法:

WebService方法列表

使用visual studio新建一个.net web项目。

使用webservice服务,使用Web服务的流程是:添加现有WebService引用->客户端调用。

新建ashx文件:

新建一般处理程序

新建handler部分代码:

/// <summary>

/// 登录接口封装

/// </summary>

public class Login : BaseHandler

{

public override void ProcessRequest(HttpContext context)

{

//传入webservice参数

string username = Request.Params["username"];

string password = Request.Params["password"];

//调用webservice

string result = client.Login(username, password);

Response.Write(result);

}

public override bool IsReusable

{

get

{

return false;

}

}

}

BaseHandler部分主要代码:

public class BaseHandler:IHttpHandler

{

#region attributes

protected HttpRequest Request;

protected HttpResponse Response;

protected HttpServerUtility Server = HttpContext.Current.Server;

//具体类名,请根据实际情况修改

protected WebService1SoapClient client; //webservice引用类

protected Result result = new Result();

protected string param = string.Empty;

#endregion

#region constructor

public BaseHandler()

{

Request = HttpContext.Current.Request;

Response = HttpContext.Current.Response;

Response.ContentType = "application/json";

client = new WebService1SoapClient();

}

#endregion

#region methods

public virtual bool IsReusable

{

get { return true; }

}

public virtual void ProcessRequest(HttpContext context)

{

//throw new NotImplementedException();

}

#endregion

}

这样一来,通过对接口进行二次封装,使返回结果为json格式,可以直接通过js在客户端解析。

对于第三方提供的接口,不管是xml还是json格式,最好还是对接口进行封装后再进行调用。

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接