c#使用Json

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   使用   sp   

AJAX傳遞複雜資料如果自己進行格式定義的話會經曆組裝、解析的過程,因此AJAX中有一個事實上
的資料轉送標準JSon。 
Json將複雜物件序列化為一個字串,在瀏覽器端再將字串還原序列化為JavaScript可以讀取的對象。
看一下Json的格式。Json被幾乎所有語言支援。 
C#中將.Net對象序列化為Json字串的方法: 
JavaScriptSerializer().Serialize(p),JavaScriptSerializer在System.Web.Extensions.dll中,
是.Net3.x 中新增的類,如果在 .Net2.0中則需要用第三方的組件。 
JQuery AJAX得到的data是Json格式資料,用 $.parseJSON(data)方法將JSon格式資料解析為JavaScript對象 
可以在post函數 後一個函數傳遞"json"則data就是還原序列化以後的對象,免去了parseJSON

案例:用Json將類返回給用戶端,使用JQurey
1.處理頁設定 Json1.ashx

public void ProcessRequest(HttpContext context)    {       context.Response.ContentType = "text/plain";       JavaScriptSerializer jss = new JavaScriptSerializer();    //建立 JavaScriptSerializer       string  json = jss.Serialize(new person(){Name="xgao",Age=18 });       context.Response.Write(json);    }    public class person    {       public string Name { get; set; }       public int Age { get; set; }    }

2.JAVAscript設定

    <script type="text/javascript">        $(function() {            $.post("Json1.ashx", function(data, state) {                if (state == "success") {                    var person = $.parseJSON(data);    //利用parseJSON進行轉換                    alert(person.Name);                    alert(person.Age);                }            });        });    </script>

 

c#使用Json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.