webservice返回xml轉json

JSON XML Visual Studio 技術 太陽照壞人 太陽照壞人 2017-08-27

現在使用webservice開發的項目仍然比較多,但由於json的廣泛使用,雖然項目採用webservice,但是實際上很多的返回值格式已經是json。但是webservice最終的返回結果卻仍然是xml格式的,而無法再客戶端直接獲取到json格式。接下來就以.net為例說明一下如何將xml返回的json提取出來,直接在客戶端以json格式直接使用。

如WebService有以下方法:

webservice返回xml轉json

WebService方法列表

使用visual studio新建一個.net web項目。

使用webservice服務,使用Web服務的流程是:添加現有WebService引用->客戶端調用。

webservice返回xml轉json

新建ashx文件:

webservice返回xml轉json

新建一般處理程序

新建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格式,最好還是對接口進行封裝後再進行調用。

相關推薦

推薦中...