ExtJs WebService Json序列化(扩展JavaScriptSerializer类)收藏
 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">
<!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">
<html xmlns="http://www.w3.org/1999/xhtml"> <head>
<head> <title>无标题页</title>
    <title>无标题页</title> <script src="ExtJs/ext-base.js" type="text/javascript"></script>
    <script src="ExtJs/ext-base.js" type="text/javascript"></script> <script src="ExtJs/ext-all.js" type="text/javascript"></script>
    <script src="ExtJs/ext-all.js" type="text/javascript"></script> </head>
</head> <body>
<body> <input id="Button1" onclick="getValue();" type="button" value="返回" />
    <input id="Button1" onclick="getValue();" type="button" value="返回" />    <textarea id="log" cols="40" rows="10"></textarea>
    <textarea id="log" cols="40" rows="10"></textarea> 
     <script type="text/javascript">
    <script type="text/javascript"> <!--
    <!-- function getValue()
    function getValue() {
    { Ext.Ajax.request(
        Ext.Ajax.request( {
        { method:"post",
            method:"post", url:"test.asmx/GetData",
            url:"test.asmx/GetData", success:ExtSuccess,
            success:ExtSuccess, headers:{'Content-Type':'application/json;utf-8'}//在这里一定要指定头信息为json,否则将返回的是XML,而不是Json
            headers:{'Content-Type':'application/json;utf-8'}//在这里一定要指定头信息为json,否则将返回的是XML,而不是Json }
        } )
        ) }
    }     function ExtSuccess(result,request)
    function ExtSuccess(result,request) {
    { var textArea = Ext.get('log').dom;
        var textArea = Ext.get('log').dom;                 textArea.value += result.responseText + " ";
                textArea.value += result.responseText + " "; //Ext.MessageBox.alert('Success', 'Data return from the server: '+ result.responseText);
                //Ext.MessageBox.alert('Success', 'Data return from the server: '+ result.responseText);          doJSON(result.responseText);
                doJSON(result.responseText); }
    } 
     
     function doJSON(stringData) {
    function doJSON(stringData) {     try {
        try { //这里可能麻烦一点,需要将返回的数据进行两次Json序列化
            //这里可能麻烦一点,需要将返回的数据进行两次Json序列化 //第二次转化的对象是stringData.d, d是ExtJs内部定义的属性
            //第二次转化的对象是stringData.d, d是ExtJs内部定义的属性 var jsonData = Ext.util.JSON.decode(stringData);
            var jsonData = Ext.util.JSON.decode(stringData);             jsonData = Ext.util.JSON.decode(jsonData.d);
            jsonData = Ext.util.JSON.decode(jsonData.d);             for(var i in jsonData)
            for(var i in jsonData) {
            { alert(i+":"+jsonData[i]);
                alert(i+":"+jsonData[i]); }
            }             }
        } catch (err) {
        catch (err) { }
        } }
    }
 //-->
    //-->     </script>
    </script> </body>
</body> </html>
</html>
然后我们加入要引用的ext-base.js和ext-all.js两个ExtJs文件,这两个文件需要读者到www.extjs.com去下载.
接下来我们创建一个test.asmx文件,代码如下:
 using System;
using System; using System.Collections;
using System.Collections; using System.ComponentModel;
using System.ComponentModel; using System.Data;
using System.Data; using System.Linq;
using System.Linq; using System.Web;
using System.Web; using System.Web.Services;
using System.Web.Services; using System.Web.Services.Protocols;
using System.Web.Services.Protocols; using System.Xml.Linq;
using System.Xml.Linq; using System.Web.Script.Services;
using System.Web.Script.Services; using System.Collections.Generic;
using System.Collections.Generic; using System.ServiceModel.Web;
using System.ServiceModel.Web; using System.ServiceModel.Dispatcher;
using System.ServiceModel.Dispatcher; using Component;
using Component; namespace WebApplication1
namespace WebApplication1 {
{ /// <summary>
    /// <summary> /// test 的摘要说明
    /// test 的摘要说明 /// </summary>
    /// </summary> [WebService(Namespace = "http://tempuri.org/")]
    [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ScriptService]
    [ScriptService] [ToolboxItem(false)]
    [ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 public class test : System.Web.Services.WebService
    public class test : System.Web.Services.WebService {
    { [WebMethod]
        [WebMethod]         public string GetData()
        public string GetData() {
        { var obj = new { obj = new[] { new { name = "a", id = 1 }, new { name = "b", id = 2 } } };
            var obj = new { obj = new[] { new { name = "a", id = 1 }, new { name = "b", id = 2 } } }; Dictionary<string, object> dic = new Dictionary<string, object>();
            Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add("p1",1);
            dic.Add("p1",1); dic.Add("p2",2);
            dic.Add("p2",2);         return obj.toJson(new { p1 = 1 }, new { p2 = 2 });
            return obj.toJson(new { p1 = 1 }, new { p2 = 2 }); }
        } 
         }
    } }
}
接下来创建一个ExtendMethod.cs文件,存放Json序列化的扩展方法
 using System;
using System; using System.Collections.Generic;
using System.Collections.Generic; using System.Linq;
using System.Linq; using System.Text;
using System.Text; using System.Web.Script.Serialization;
using System.Web.Script.Serialization; using System.Collections;
using System.Collections; using System.Reflection;
using System.Reflection; namespace Component
namespace Component {
{ public static class ExtendMethod
    public static class ExtendMethod {
    { /// <summary>
        /// <summary> /// 返回Json序列
        /// 返回Json序列 /// parms字典
        /// parms字典 /// Key:Json对象名
        /// Key:Json对象名 /// Value:Json对象值
        /// Value:Json对象值 /// </summary>
        /// </summary> /// <param name="This"></param>
        /// <param name="This"></param> /// <param name="parms">需要加入的对象</param>
        /// <param name="parms">需要加入的对象</param> /// <returns></returns>
        /// <returns></returns> public static string toJson(this object This,Dictionary<string,object> parms)
        public static string toJson(this object This,Dictionary<string,object> parms) {
        { JavaScriptSerializer json = new JavaScriptSerializer();
            JavaScriptSerializer json = new JavaScriptSerializer(); var ds = new { source=This};
            var ds = new { source=This}; 
            
 Dictionary<object,object> dic = new Dictionary<object,object>();
            Dictionary<object,object> dic = new Dictionary<object,object>(); dic.Add("source",This);
            dic.Add("source",This);
 foreach (KeyValuePair<string, object> key in parms)
            foreach (KeyValuePair<string, object> key in parms) {
            { dic.Add(key.Key,key.Value);
                dic.Add(key.Key,key.Value); }
            }             return json.Serialize(dic);
            return json.Serialize(dic); }
        }
 /// <summary>
        /// <summary> /// 返回Json序列
        /// 返回Json序列 /// parms:加入的对象将与this对象同级
        /// parms:加入的对象将与this对象同级 /// 未完成
        /// 未完成 /// </summary>
        /// </summary> /// <param name="This"></param>
        /// <param name="This"></param> /// <param name="parms">需要加入的对象</param>
        /// <param name="parms">需要加入的对象</param> /// <returns></returns>
        /// <returns></returns> public static string toJson(this object This, params object[] parms)
        public static string toJson(this object This, params object[] parms) {
        { JavaScriptSerializer json = new JavaScriptSerializer();
            JavaScriptSerializer json = new JavaScriptSerializer(); Dictionary<string, object> dic = new Dictionary<string, object>();
            Dictionary<string, object> dic = new Dictionary<string, object>(); dic.Add("source", This);
            dic.Add("source", This); foreach (object i in parms)
            foreach (object i in parms) {
            { Type t = i.GetType();
                Type t = i.GetType(); PropertyInfo[] myproperties = t.GetProperties();
                PropertyInfo[] myproperties = t.GetProperties(); dic.Add(myproperties[0].Name, myproperties[0].GetValue(i, null));
                dic.Add(myproperties[0].Name, myproperties[0].GetValue(i, null)); }
            }
 return json.Serialize(dic);
            return json.Serialize(dic); }
        } }
    } }
} 
                    
                     
                    
                 
                    
                
 
 
     
     
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号