您的位置:首页 > Web前端 > JavaScript

ExtJs WebService Json序列化(扩展JavaScriptSerializer类)收藏

2008-07-16 21:27 316 查看
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>无标题页</title>

<script src="ExtJs/ext-base.js" type="text/javascript"></script>

<script src="ExtJs/ext-all.js" type="text/javascript"></script>

</head>

<body>

<input id="Button1" onclick="getValue();" type="button" value="返回" />

<textarea id="log" cols="40" rows="10"></textarea>

</body>

</html>

然后我们加入要引用的ext-base.js和ext-all.js两个ExtJs文件,这两个文件需要读者到www.extjs.com去下载.

接下来我们创建一个test.asmx文件,代码如下:

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

接下来创建一个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

...{


public static class ExtendMethod




...{




/**//// <summary>


/// 返回Json序列


/// parms字典


/// Key:Json对象名


/// Value:Json对象值


/// </summary>


/// <param name="This"></param>


/// <param name="parms">需要加入的对象</param>


/// <returns></returns>


public static string toJson(this object 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>


public static string toJson(this object This, params object[] 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);


}


}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: