using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Xml.Linq; using System.Web.Script.Services; using System.Collections.Generic; using System.ServiceModel.Web; using System.ServiceModel.Dispatcher; using Component; namespace WebApplication1 ...{ /**////<summary> /// test 的摘要说明 ///</summary> [WebService(Namespace ="http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService] [ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 publicclass test : System.Web.Services.WebService ...{ [WebMethod] publicstring GetData() ...{ var obj =new...{ obj =new[] ...{ new...{ name ="a", id =1 }, new...{ name ="b", id =2 } } }; Dictionary<string, object> dic =new Dictionary<string, object>(); dic.Add("p1",1); dic.Add("p2",2); return obj.toJson(new...{ p1 =1 }, new...{ p2 =2 }); } } }
接下来创建一个ExtendMethod.cs文件,存放Json序列化的扩展方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Script.Serialization; using System.Collections; using System.Reflection; namespace Component ...{ publicstaticclass ExtendMethod ...{ /**////<summary> /// 返回Json序列 /// parms字典 /// Key:Json对象名 /// Value:Json对象值 ///</summary> ///<param name="This"></param> ///<param name="parms">需要加入的对象</param> ///<returns></returns> publicstaticstring toJson(thisobject This,Dictionary<string,object> parms) ...{ JavaScriptSerializer json =new JavaScriptSerializer(); var ds =new...{ source=This}; Dictionary<object,object> dic =new Dictionary<object,object>(); dic.Add("source",This); foreach (KeyValuePair<string, object> key in parms) ...{ dic.Add(key.Key,key.Value); } return json.Serialize(dic); } /**////<summary> /// 返回Json序列 /// parms:加入的对象将与this对象同级 /// 未完成 ///</summary> ///<param name="This"></param> ///<param name="parms">需要加入的对象</param> ///<returns></returns> publicstaticstring toJson(thisobject This, paramsobject[] parms) ...{ JavaScriptSerializer json =new JavaScriptSerializer(); Dictionary<string, object> dic =new Dictionary<string, object>(); dic.Add("source", This); foreach (object i in parms) ...{ Type t = i.GetType(); PropertyInfo[] myproperties = t.GetProperties(); dic.Add(myproperties[0].Name, myproperties[0].GetValue(i, null)); } return json.Serialize(dic); } } }