现在项目要求跨平台,数据共享,json结构的数据结果必不可少。而其中跨平台自然用到webservice技术,根据webservice特性传送数据为XML结构,如果各平台使用不可避免要进行XML转换为json数据,往往较为麻烦,为后面日常维护带来不便。能不能使得各个平台调用webservice时候直接返还json数据呢,经过研究发现,是可行的,技术实现如下(以C#做webservice为例)
通常webservice 接口定义
[WebMethod] public string GetName() { return "Hello World Produce"; }
返还
<? xml version="1.0" encoding="utf-8" ?> < string xmlns =" http://tempuri.org/ " > Hello World Produce </ string > 其实 问题就出现在 return 语句上,经过改造,写一个静态方法用来替换 return public static class WebServiceContext { public static void GetJsonData(System.Web.Services.WebService wb,string jsonData) { //System.Web.Services.WebService wb = new System.Web.Services.WebService(); wb.Context.Response.Charset = "utf-8"; wb.Context.Response.ContentEncoding = System.Text.Encoding.UTF8; wb.Context.Response.Write(jsonData); wb.Context.Response.End(); } } z这样返还结果就直接是json数据了。