ExtJs WebService Json序列化(扩展JavaScriptSerializer类)收藏
ExtJs WebService Json序列化(扩展JavaScriptSerializer类)
新一篇: ExtJs Ajax的WCF服务 之 Ext.grid 控件显示 | 旧一篇: Extjs 数据读取对象ArrayReader/JsonReader/XmlReader
今天我们来探讨一下关于 使用JavaScriptSerializer的Serialize方法进行Json序列化.
在这里我们要用到反射,所以,对于反射也可以顺便学习一下.
注意,我这里是用Vs2008来编写的,所以Vs2008以前的版本,需要读者自己相应的改一下,~_~!
首先我们创建一个webapplication工程,
添加一个WebService.htm文件,
页面代码如下:
<!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>
<script type="text/javascript">
<!--
function getValue()
{
Ext.Ajax.request(
{
method:"post",
url:"test.asmx/GetData",
success:ExtSuccess,
headers:{'Content-Type':'application/json;utf-8'}//在这里一定要指定头信息为json,否则将返回的是XML,而不是Json
}
)
}
function ExtSuccess(result,request)
{
var textArea = Ext.get('log').dom;
textArea.value += result.responseText + " ";
//Ext.MessageBox.alert('Success', 'Data return from the server: '+ result.responseText);
doJSON(result.responseText);
}
function doJSON(stringData) {
try {
//这里可能麻烦一点,需要将返回的数据进行两次Json序列化
//第二次转化的对象是stringData.d, d是ExtJs内部定义的属性
var jsonData = Ext.util.JSON.decode(stringData);
jsonData = Ext.util.JSON.decode(jsonData.d);
for(var i in jsonData)
{
alert(i+":"+jsonData[i]);
}
}
catch (err) {
}
}
//-->
</script>
</body>
</html>
<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>
<script type="text/javascript">
<!--
function getValue()
{
Ext.Ajax.request(
{
method:"post",
url:"test.asmx/GetData",
success:ExtSuccess,
headers:{'Content-Type':'application/json;utf-8'}//在这里一定要指定头信息为json,否则将返回的是XML,而不是Json
}
)
}
function ExtSuccess(result,request)
{
var textArea = Ext.get('log').dom;
textArea.value += result.responseText + " ";
//Ext.MessageBox.alert('Success', 'Data return from the server: '+ result.responseText);
doJSON(result.responseText);
}
function doJSON(stringData) {
try {
//这里可能麻烦一点,需要将返回的数据进行两次Json序列化
//第二次转化的对象是stringData.d, d是ExtJs内部定义的属性
var jsonData = Ext.util.JSON.decode(stringData);
jsonData = Ext.util.JSON.decode(jsonData.d);
for(var i in jsonData)
{
alert(i+":"+jsonData[i]);
}
}
catch (err) {
}
}
//-->
</script>
</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
{
/// <summary>
/// test 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
[ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
public class test : System.Web.Services.WebService
{
[WebMethod]
public string 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 });
}
}
}
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 服务,请取消对下行的注释。
public class test : System.Web.Services.WebService
{
[WebMethod]
public string 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
{
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);
}
}
}
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);
}
}
}