AJAX調用方式總結


      最近用了近兩天的時間對AJAX的知識進行了一個梳理,覺得是時候對AJAX的相關知識點做個總結了.....這當然也就是本篇博客的主旨了....我也不是很贊成用長篇大論來講述什么是AJAX,怎么使用AJAX,這樣我總覺得太理論化了,接受起來會有一定的難度...所以,本篇博客的另一個主旨是:從實例入手,由淺到深.....好了,直接開始入手吧...在之前的一篇文章中講解了原生態AJAX來獲取數據》的一個小實例,從“原生態”就可以看出,就是AJAX的最基礎的形態了....

 

實例一:省份-城市的聯級下拉框 

利用AJAX來獲取數據實現聯級下拉框,當省份下拉框的選項發生變化時,城市的選項對應變化,效果如圖:

 

      我們首先來實現后台,先將數據准備好了在實現前台獲取數據,【考慮:當我們頁面登錄的時候,我們需要獲取的數據】 1).省份框中的省份; 2).因為登錄時省份框的第一項選中,所以還需要第一個省份所對應的城市名,好了,需求知道了,代碼就好寫了,直接貼上后台代碼:

省份-城市聯級下拉框后台
 1  protected  void Page_Load( object sender, EventArgs e)
 2         {
 3              if (Request.QueryString[ " provid "] !=  null)
 4             {
 5                  // 首先獲取傳遞過來的參數值
 6                   string provId = Request.QueryString[ " provid "].ToString();
 7 
 8                  // 查詢所有城市
 9                   string sqlprov =  " select * from Provice ";
10                 SqlDataReader reader = DbHelperSQL.ExecuteReader(sqlprov);
11                  string resultProv =  "";
12                  while (reader.Read())
13                 {
14                      string id = reader[ 0].ToString();
15                      string provName = reader[ 1].ToString();
16 
17                      // 字符串拼接,為了前台獲取時可以切分獲取對應數據,用 '|' 來隔離 各個省份
18                      resultProv +=  " | " +  string.Format( " {0},{1} ", id, provName);
19                 }
20                 reader.Close();
21 
22                  // 根據省份框的ID來獲取對應的城市名
23                   string sqlcity = string.Format( " select * from City where Proid='{0}' ",provId);
24                 SqlDataReader readercity = DbHelperSQL.ExecuteReader(sqlcity);
25                  string resultCity =  "";
26                  while (readercity.Read())
27                 {
28                      string cityId = readercity[ 1].ToString();
29                      string cityName = readercity[ 2].ToString();
30 
31                      // 同樣用字符串拼接 用 '|' 來隔離 同一省份 的各個城市
32                      resultCity +=  " | " +  string.Format( " {0},{1} ", cityId, cityName);
33                 }
34 
35                  // 去除第一個 '|' ,並且在最后拼接上 '&' 來區分省份和城市
36                  resultProv = resultProv.Substring( 1) +  " & ";
37 
38                  // 最后的結果形式為【id,省份名|id2,省份名2|....&id,城市名|id2,城市名2|.....】
39                   string result = resultProv + resultCity.Substring( 1);
40 
41                 Response.Write(result);
42                 Response.End();
43             }
44         }

后台代碼其實很簡單,就是根據傳過來的參數從數據庫獲取對應的數據,但是這里我們把獲取到得數據最后都用字符串拼接起來了,而且是有規律的拼接,這是為什么呢?其實在注釋上已經講明了,就是為了方便前台獲取對應的數據了,因為我們是使用后台返回文本形式的數據,這就是為什么我們拼接字符串了。。

接下來我們來實現前台,前台主要的任務就是獲取后台返回的數據,並實現綁定......也是分塊貼上代碼

實例化XmlHttpRequest對象
 1  // 實例化XmlHttpRequest對象
 2    var xhr =  null;
 3         function CreateXhr() {
 4              if (window.ActiveXObject) 
 5             {
 6                  try
 7                 {
 8                     xhr =  new ActiveXObject( " Microsoft.XMLHTTP ");
 9                 }
10                  catch (e) 
11                 {
12                      try
13                     {
14                         xhr =  new ActiveXObject( " Msxml2.XMLHTTP ");
15                     }
16                      catch (e) 
17                     {
18                         xhr =  null;
19                     }
20                 }
21             }
22              if (window.XMLHttpRequest) {
23                 xhr =  new XMLHttpRequest();
24             }
25 
26              return xhr;
27         }

 當頁面載入時,實現省份框以及第一個省份對應的城市框的綁定,代碼:

載入綁定
 1   // 載入綁定省份 
 2          function getLoadProv() {
 3             CreateXhr();
 4             xhr.onreadystatechange = WatchState;
 5             xhr.open( " get "" getProvCity.aspx?provid=1&time= " +  new Date());
 6             xhr.send( null);
 7         }
 8 
 9          // 監聽載入綁定時狀態
10          function WatchState() {
11              if (xhr.readyState ==  4 && xhr.status ==  200) {
12                  // 1,**|2,**&1,##|2,##
13                   var result = xhr.responseText;
14                  var provs = result.split( ' & ')[ 0].split( ' | ');
15                  var citys = result.split( ' & ')[ 1].split( ' | ');
16 
17                  // 省份下拉框清空
18                  document.forms[ 0].prov.length =  0;
19 
20                  // 綁定省份框
21                   for ( var i =  0; i < provs.length; i++) {
22                      var prov = provs[i].split( ' , ');
23                      // 實例化一個選項
24                       var op =  new Option();
25                     op.value = prov[ 0];
26                     op.text = prov[ 1];
27                     document.forms[ 0].prov.options.add(op);
28                 }
29 
30                  // 城市下拉框清空
31                  document.forms[ 0].city.length =  0;
32 
33                  // 綁定城市框
34                   for ( var j =  0; j < citys.length; j++) {
35                      var city = citys[j].split( ' , ');
36                      var op =  new Option();
37                     op.value = city[ 0];
38                     op.text = city[ 1];
39                     document.forms[ 0].city.options.add(op);
40                 }                
41             }
42         }

 當省份框的項發生變化時實現聯級變化,代碼:

省份變化綁定
 1          // 獲取城市
 2          function GetCity() {
 3            
 4              // 獲取省份框選中的值
 5               var provId = document.forms[ 0].prov.value;
 6 
 7             CreateXhr();
 8             xhr.onreadystatechange = UpdateCity;
 9             xhr.open( " get "" getProvCity.aspx?provid= " + provId +  " &time= " +  new Date());
10             xhr.send( null);
11         }
12 
13          // 修改城市下拉框內容
14          function UpdateCity() {
15              if (xhr.readyState ==  4 && xhr.status ==  200) {
16                  var result = xhr.responseText;
17                  var citys = result.split( ' & ')[ 1].split( ' | ');
18                  // 城市下拉框清空
19                  document.forms[ 0].city.length =  0;
20 
21                  // 綁定城市框
22                   for ( var j =  0; j < citys.length; j++) {
23                      var city = citys[j].split( ' , ');
24                      var op =  new Option();
25                     op.value = city[ 0];
26                     op.text = city[ 1];
27                     document.forms[ 0].city.options.add(op);
28                 }                
29             }

 前台html代碼:

html
 1 <body>
 2     <form id= " form1 " runat= " server ">
 3     <div>
 4         < select id= " prov " onchange= " GetCity(); ">
 5         </ select>
 6         < select id= " city ">
 7         </ select>
 8     </div>
 9     </form>
10 </body>

 

 

實例二:利用$.get,$.post方法獲取當前時間

$.get():

定義 get()方法通過遠程HTTP GET請求載入信息 

語法:$(selector).get(url,data,success(response,status,xhr),dataType)

參數

url:必須,請求發送的地址。

data:可選,發送到服務器的數據。

success:可選,請求成功時運行的函數

             1).response:包含結果的數據

             2).status:包含請求的狀態

             3).xhr:包含XmlHttpRequest對象

dataType:服務器響應的數據類型,默認將智能判斷

 

$.post()

定義 post()方法通過遠程HTTP Post請求載入信息 

語法:$(selector).post(url,data,success(data,status,jqXHR),dataType)

參數

url:必須,請求發送的地址。

data:可選,發送到服務器的數據。

success:可選,請求成功時運行的函數

             1).data:包含結果的數據

             2).status:包含請求的狀態

             3).jqXHR:包含XmlHttpRequest對象

dataType:服務器響應的數據類型,默認將智能判斷

 

由於實例相當簡單,直接上所有代碼:

后台
 1   protected  void Page_Load( object sender, EventArgs e)
 2         {
 3              string time =  "";
 4              // Get
 5               if (Request.QueryString[ " time "]!= null)
 6             {
 7                 time =  " Get: "+ Request.QueryString[ " time "].ToString();
 8             }
 9              // Post
10               if (Request.Form[ " time "] !=  null)
11             {
12                 time =  " Post: " + Request.Form[ " time "].ToString();
13             }
14 
15             Response.Write(time +  "   現在: " + DateTime.Now.ToString());
16             Response.End();
17         }

前台獲取時間
 1    <script src= " ../Scripts/jquery-1.8.0.js " type= " text/javascript "></script>
 2     <script type= " text/javascript ">
 3         $(function () {
 4              // 參數:直接在頁面之后加?拼加
 5              $( " #btnGet ").click(function () {
 6                 $. get( " data.aspx?time= " +  new Date(), Succeed);
 7             });
 8 
 9              // 參數:使用鍵值來表示需要傳遞的參數
10              $( " #btnPost ").click(function () {
11                 $.post( " data.aspx ", { time:  new Date() }, Succeed);
12             });
13         });
14 
15         function Succeed(result) {
16             $( " #tbShow ").val(result);
17         }
18     </script>
html
<body>
    <form id= " form1 " runat= " server ">
        <div>
          <input type= " text " id= " tbShow "/>
          <input type= " button " id= " btnGet " value= " get方法 " />
          <input type= " button " id= " btnPost " value= " post方法 " />
          <input type= " button " id= " btnAjax " value= " ajax方法 " />
        </div>
    </form>
</body>

 

實例三:使用$.ajax實現獲取后台數據,后台返回數據格式為text,json,xml三種類型

$.ajax()

定義 ajax()方法通過遠程HTTP請求載入信息 

語法:Jquery.ajax([settings])

常用參數[settings]--用於配置Ajax的鍵值對請求

url:必須,請求發送的地址

type: 請求方式

data:可選,發送到服務器的數據

success:可選,請求成功時運行的函數

             1).data:包含結果的數據

             2).status:包含請求的狀態

             3).jqXHR:包含XmlHttpRequest對象

dataType:服務器響應的數據類型,默認將智能判斷

其余參數詳情參見:http://www.w3school.com.cn/jquery/ajax_ajax.asp

 

1>.test格式 --獲取時間的時,分,秒

后台代碼:

text后台
 1   public  partial  class textData : System.Web.UI.Page
 2     {
 3          protected  void Page_Load( object sender, EventArgs e)
 4         {
 5              string hour = DateTime.Now.Hour.ToString();
 6              string minute = DateTime.Now.Minute.ToString();
 7              string second = DateTime.Now.Second.ToString();
 8 
 9              string textStr = hour +  " / " + minute +  " / " + second;
10 
11             Response.Write(textStr);
12 
13             Response.End();
14         }
15     }

前台獲取代碼:

text前台
 1     <script src= " ../Scripts/jquery-1.8.0.js " type= " text/javascript "></script>
 2     <script type= " text/javascript ">
 3         $(function () {
 4             $( " #btnText ").click(function () {
 5                 $.ajax({
 6                     url:  " textData.aspx ",
 7                     type:  " get ",
 8                     dataType:  " text ",
 9                     success: textSucceed,
10                     error: Error
11                 });
12             });
13 
14         });
15 
16          // 成功
17          function textSucceed(result) {
18             $( " #tbShow ").val(result);
19         }
20 
21          // 錯誤函數
22          function Error() {
23             alert( " Error!!! ");
24         }
25     </script>

 

2>.Json格式 --獲取時間的時,分,秒

我們需要在后台返回Json格式的數據,添加一個dll鏈接庫,類似.Net中處理Json數據的API ,如圖:

Json格式后台代碼:

Json后台
 1  // 添加引用
 2  using Newtonsoft.Json;
 3 
 4  namespace AJAX.Json
 5 {
 6      public  partial  class jsonData : System.Web.UI.Page
 7     {
 8          protected  void Page_Load( object sender, EventArgs e)
 9         {
10              string hour = DateTime.Now.Hour.ToString();
11              string minute = DateTime.Now.Minute.ToString();
12              string second = DateTime.Now.Second.ToString();
13 
14              // 匿名類型
15               var time =  new { h = hour, m = minute, s = second };
16 
17              // 轉Json格式
18               var jsonStr = JsonConvert.SerializeObject( new[] { time });
19 
20             Response.Write(jsonStr);
21 
22             Response.End();
23         }
24     }
25 }

 Json格式前台代碼:

Json前台
 1 <script src= " ../Scripts/jquery-1.8.0.js " type= " text/javascript "></script>
 2     <script type= " text/javascript ">
 3         $( " #btnJson ").click(function () {
 4             $.ajax({
 5                 url:  " jsonData.aspx ",
 6                 type:  " get ",
 7                 dataType:  " json ",
 8                 success: jsonSuccess,
 9                 error: Error
10             });
11         });
12 
13          // 成功
14          function jsonSuccess(result) {
15              // [{h:10,m:20,s:30}]
16               // key:數組元素下標-此時為0
17               // value:{ h:10,m:20,s:30 }
18              $.each(result, function (key, value) {
19                  var h = value.h;
20                  var m = value.m;
21                  var s = value.s;
22                 $( " #tbShow ").val(h +  " : " + m +  " : " + s);
23             });
24         }
25        
26          // 錯誤函數
27          function Error() {
28             alert( " Error!!! ");
29         }
30     </script>

 

3>.xml格式--獲取用戶名,出生年月

 Xml格式后台代碼:

xml后台
 1  // 添加引用
 2  using System.Xml;
 3 
 4  namespace AJAX.Ajax_Xml
 5 {
 6      public  partial  class XmlData : System.Web.UI.Page
 7     {
 8          protected  void Page_Load( object sender, EventArgs e)
 9         {
10              string name =  " zld ";
11              string birth =  " 1990-1-8 ";
12 
13              // 第一種:直接字符串拼接
14               string xmlStr =  " <?xml version=\"1.0\" encoding=\"utf-8\" ?><root><Name> " + name +  " </Name><Birth> " + birth +  " </Birth></root> ";
15 
16              // 第二種:XmlDocument創建
17 
18               // 創建文檔
19              XmlDocument xmlDocument =  new XmlDocument();
20              // 文檔頭聲明
21              XmlDeclaration xd = xmlDocument.CreateXmlDeclaration( " 1.0 ", " utf-8 ", null);
22             xmlDocument.AppendChild(xd);
23 
24              // 添加根節點
25              XmlElement root = xmlDocument.CreateElement( " root ");
26             xmlDocument.AppendChild(root);
27 
28              // 給根節點添加子節點
29              XmlElement node1 = xmlDocument.CreateElement( " Name ");
30             node1.InnerText = name;
31             root.AppendChild(node1);
32 
33             XmlElement node2 = xmlDocument.CreateElement( " Birth ");
34             node2.InnerText = birth;
35             root.AppendChild(node2);
36 
37              // 獲取節點元素
38               string xmlStr2 = xmlDocument.OuterXml;
39 
40             Response.Write(xmlStr2);
41             Response.End();
42 
43         }
44     }
45 }

 Xml格式前台代碼:

Xml前台
 1 <script src= " ../Scripts/jquery-1.8.0.js " type= " text/javascript "></script>
 2     <script type= " text/javascript ">
 3         $(function () {
 4             $( " #btnXml ").click(function () {
 5                 $.ajax({
 6                     url:  " XmlData.aspx ",
 7                     type:  " get ",
 8                     dataType:  " xml ",
 9                     success: Success,
10                     error: function (result) {
11                         alert( " 相應內容非xml格式! ");
12                     }
13                 });
14             });
15         });
16 
17         function Success(xmlResult) {
18              // 獲取返回結果
19               var result = xmlResult;
20              // 找尋根節點並循環遍歷
21              $(result).find( ' root ').each(function (key) {
22                  // 獲取子節點名為Name的值
23                   var name = $( this).children( " Name ").text();
24                  // 獲取子節點名為Birth的值
25                   var birth = $( this).children( " Birth ").text();
26                 $( " #tbShow ").val(name +  " : " + birth);
27             });
28         }
29     </scri


實例四:ajax調用wcf獲取數據

首先貼上模塊圖:

 

首先定義好數據契約和操作契約,貼上StudentService.svc代碼:

StudentService.svc
 1  namespace ajaxwcf
 2 {
 3     [ServiceContract(Namespace =  "")]
 4     [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 5      public  class StudentService
 6     {
 7          //  要使用 HTTP GET,請添加 [WebGet] 特性。(默認 ResponseFormat 為 WebMessageFormat.Json)
 8           //  要創建返回 XML 的操作,
 9           //      請添加 [WebGet(ResponseFormat=WebMessageFormat.Xml)],
10           //      並在操作正文中包括以下行:
11           //          WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
12          [OperationContract]
13          // 獲取學生數據
14           public List<Student> GetStudents()
15         {
16              string sqlConn = ConfigurationManager.ConnectionStrings[ " SqlConn "].ConnectionString;
17             SqlConnection conn =  new SqlConnection(sqlConn);
18             SqlDataAdapter da =  new SqlDataAdapter( " select * from AJAX_Tab ", conn);
19             DataSet ds =  new DataSet();
20             da.Fill(ds);
21             List<Student> Stulis =  new List<Student>();
22             DataTable dt = ds.Tables[ 0];
23             Student student =  null;
24              foreach (DataRow row  in dt.Rows)
25             {
26                 student =  new Student();
27                 student.Sname = row[ " sname "].ToString();
28                 student.Sage = row[ " sage "].ToString();
29                 student.Sadd = row[ " sadd "].ToString();
30 
31                 Stulis.Add(student);
32             }
33 
34              return Stulis;
35         }
36     }
37 
38      // 數據契約
39      [DataContract]
40      public  class Student
41     {
42          private  string sname;
43 
44         [DataMember]
45          public  string Sname
46         {
47              get {  return sname; }
48              set { sname = value; }
49         }
50          private  string sage;
51 
52         [DataMember]
53          public  string Sage
54         {
55              get {  return sage; }
56              set { sage = value; }
57         }
58          private  string sadd;
59 
60         [DataMember]
61          public  string Sadd
62         {
63              get {  return sadd; }
64              set { sadd = value; }
65         }
66     }
67 }

web.config中進行配置,上代碼:

web.config
 1  <system.serviceModel>
 2         <behaviors>
 3             <endpointBehaviors>
 4                 <behavior name= " ajaxwcf.StudentServiceAspNetAjaxBehavior ">
 5                     <enableWebScript />
 6                 </behavior>
 7             </endpointBehaviors>
 8             <serviceBehaviors>
 9                 <behavior name= " MyServiceTypeBehaviors ">
10                     <serviceMetadata httpGetEnabled= " true " />
11                 </behavior>
12                 <behavior name= "">
13                     <serviceMetadata httpGetEnabled= " true " />
14                     <serviceDebug includeExceptionDetailInFaults= " false " />
15                 </behavior>
16             </serviceBehaviors>
17         </behaviors>
18         <serviceHostingEnvironment aspNetCompatibilityEnabled= " true "
19             multipleSiteBindingsEnabled= " true " />
20         <services>
21             <service name= " ajaxwcf.StudentService " behaviorConfiguration= " MyServiceTypeBehaviors ">
22                 <endpoint address= "" behaviorConfiguration= " ajaxwcf.StudentServiceAspNetAjaxBehavior "
23                     binding= " webHttpBinding " contract= " ajaxwcf.StudentService " />
24             </service>
25         </services>
26     </system.serviceModel>

好了,這樣wcf就配置好了,接下去就是頁面端的調用了,貼上ajax_wcf.aspx前台頁面代碼:

ajax_wcf.aspx前台
 1  <script type= " text/javascript ">
 2          // 載入WCF
 3          function loadWCF() {
 4             var student =  new StudentService();  
 5            arr = student.GetStudents(succeededCallback, filedCallback);         
 6         }
 7          // 成功
 8          function succeededCallback(result, userContext, methodName) {
 9              var arr =  new Array();
10             arr = result;
11              // 動態創建表格信息 並賦值
12               var table = document.getElementById( " ajaxTab ");
13              for ( var i =  0; i < arr.length; i++) {
14                  var tr = document.createElement( " tr ");
15                  var td1 = document.createElement( " td ");
16                 td1.innerHTML = arr[i].Sname;
17 
18                  var td2 = document.createElement( " td ");
19                 td2.innerHTML = arr[i].Sage;
20 
21                  var td3 = document.createElement( " td ");
22                 td3.innerHTML = arr[i].Sadd;
23 
24 
25                 tr.appendChild(td1);
26                 tr.appendChild(td2);
27                 tr.appendChild(td3);
28 
29                 table.appendChild(tr);
30             }
31         }
32 
33          // 失敗
34          function filedCallback(error,userContext,methodName) {
35             alert( " Error! ");
36          }

這樣整個項目就完成了,接下去貼效果:

調用前:

 

調用后:

 

實例五[補充內容]:Json格式數據的打包和解包方式

在打包和解包中,我們仍舊用到了上面提及的Json數據API,同樣要先添加引用,由於代碼都有了對應的注釋,不再多做文字的贅述,直接貼上代碼和效果吧:

代碼:

Json格式數據打包解包
 1  namespace Json打包解包方式
 2 {
 3      class Program
 4     {
 5          static  void Main( string[] args)
 6         {
 7              string name =  " zld ";
 8              int age =  23;
 9              string addr =  " nb ";
10 
11              // ----------------------匿名打包------------------- //
12               // 創建匿名類型
13               var temClass =  new { Name = name, Age = age, Addr = addr };
14            
15             Console.WriteLine( " ----------通過匿名打包------------ ");
16              // 打包成單個Json對象
17               var jsonStr1 = JsonConvert.SerializeObject(temClass);
18 
19             Console.WriteLine( " 打包單個對象后:\n{0} ", jsonStr1);
20             Console.WriteLine();
21 
22              // 打包成Json數組
23               var jsonStr2 = JsonConvert.SerializeObject( new[] { temClass,temClass });
24 
25             Console.WriteLine( " 打包Json數組后:\n{0} ", jsonStr2);
26             Console.WriteLine();
27 
28              // ----------------------匿名解包------------------- //
29              Console.WriteLine( " ----------通過匿名解包------------ ");
30              // 匿名解包
31               var temClass2 = JsonConvert.DeserializeAnonymousType(jsonStr1, temClass);
32             Console.WriteLine( " 匿名解包后:\n Name={0},Age={1},Addr={2} ",temClass2.Name,temClass2.Age,temClass2.Addr);
33             Console.WriteLine();
34 
35              // 提取局部信息
36               var temClass3 = JsonConvert.DeserializeAnonymousType(jsonStr1,  new { Name = name, Addr = addr });
37             Console.WriteLine( " 匿名解包局部信息后: \n Name={0},Addr={1} ", temClass3.Name, temClass3.Addr);
38             Console.WriteLine();
39 
40              // 解包成數組對象【jsonStr2:數組對象】
41               var temClass4 = JsonConvert.DeserializeAnonymousType(jsonStr2,  new[] { temClass });
42              // 數組 foreach循環遍歷
43               foreach( var item  in temClass4)
44             {
45                 Console.WriteLine( " 匿名解包為數組后: \n Name={0},Age={1},Addr={2} ",item.Name,item.Age,item.Addr);
46             }
47             Console.WriteLine();
48 
49              // ----------------------通過類打包------------------- //
50               // 實例化一個類對象
51              MyObj mo =  new MyObj() { Name = name, Age = age, Addr = addr };
52 
53             Console.WriteLine( " ----------通過類打包------------ ");
54              // 單個對象打包
55               var temClass5 = JsonConvert.SerializeObject(mo);
56             Console.WriteLine( " 類打包后:\n{0} ", temClass5);
57             Console.WriteLine();
58 
59              // 打包成集合(數組 泛型)
60               var temClass6 = JsonConvert.SerializeObject( new[] { mo,mo });
61             Console.WriteLine( " 類打包成數組后:\n{0} ", temClass6);
62             Console.WriteLine();
63 
64              var temClass7=JsonConvert.SerializeObject( new List<MyObj>{mo,mo});
65             Console.WriteLine( " 類打包成泛型后:\n{0} ", temClass6);
66             Console.WriteLine();
67 
68             Console.WriteLine( " ----------通過類解包------------ ");
69 
70              var temClass8 = JsonConvert.DeserializeObject<MyObj>(temClass5);
71             Console.WriteLine( " 類解包單個對象后:\n Name={0},Age={1},Addr={2} ", temClass8.Name, temClass8.Age, temClass8.Addr);
72             Console.WriteLine();
73 
74              var temClass9 = JsonConvert.DeserializeObject<List<MyObj>>(temClass6);
75              foreach(MyObj item  in temClass9)
76             {
77                 Console.WriteLine( " 類解包泛型后:\n Name={0},Age={1},Addr={2} ", item.Name, item.Age, item.Addr);
78             }
79 
80             Console.ReadKey();
81            
82         }
83     }
84 
85      // 定義一個類型
86       public  class MyObj
87     {
88          public  string Name {  getset; }
89          public  int Age {  getset; }
90          public  string Addr {  getset; }
91     }
92 }

效果圖:

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM