本來以為在client 端要傳輸JSON物件到ASP來做反序列化(Deserialize) 後來才知道做了多餘的事情
 
ASP.NET,在接收JSON物件的時候,是直接讀入JSON"字串化(stringify)"的字串
然後在伺服器端利用讀取stream的方式,把所有的值都讀進來(不使用Request.Form 或 Request.Querystring)
讀進來的字串,要確定沒有多餘的刮弧、反斜線或雙引號,在做一些JSON字串產生的時候,可能會產生一些多餘的符號,是debug的重點,必須多加注意
 
讀進JSON字串之後,就要用JavaScriptSerializer 的Deserialize 方法來把字串給parse 成物件
物件的格式要在一個class中先規定好,如果讀入的字串不符合規定,則會出現Exception
 
以下是一些程式碼
 
 
client 端,產生JSON物件並且用ajax 傳給sever 端
 
 

 

             var dataJson = { "d0": "vla0", "d1": "vla1" };

 

                $.ajax({

 

                    type: "POST",

 

                    url: "chartGenerater.aspx",

 

                    data: JSON.stringify(dataJson ).replace(/\\/ig, ""),

 

                    success: function (msg) {

 

                    },

 

                    error: function (xhr, ajaxOptions, thrownError) {

 

                        alert(xhr.status);

 

                        alert(thrownError);

 

                    }

 

                });

 

            });

 

sever 端接收JSON字串
 
要先using 一些reference ,如果顯示找不到,就要手動去加入

//Assembly: System.Runtime.Serialization
using System.Runtime.Serialization.Json;
//Assembly: System.ServiceModel.Web
using System.ServiceModel.Web;

var stream = Request.InputStream;
string json = new StreamReader(stream).ReadToEnd();

JavaScriptSerializer serializer = new JavaScriptSerializer();
DataTableJson dtJson = serializer.Deserialize<DataTableJson>(json);

Response.Write(dtJson.d0);
Response.Write(dtJson.d1);

規定JSON接收的格式

class DataTableJson{

   public string d0 { get; set; }
   public string d1 { get; set; }
}

 

格式設定上,如果JSON物件中有陣列,可以直接用array,或是用List 來接收

如果是JSON物件的陣列,就要再訂一個格式,作為陣列中物件的格式

也就是說,沒有陣列,需要訂一個格式(JSON本身)

一維陣列要訂兩個格式(JSON本身,陣列內的JSON)

二維陣列要訂三個格式...

 

arrow
arrow
    全站熱搜

    yaya741228 發表在 痞客邦 留言(0) 人氣()