zoukankan      html  css  js  c++  java
  • C#使用Json

    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>
  • 相关阅读:
    docker articles&videos
    Docker Resources
    IL-rewriting profiler
    memory dump and CLR Inside Out
    tcp/ip basics
    What Every CLR Developer Must Know Before Writing Code
    CLR profiler
    Debug CLR and mscorlib
    JIT Compiler
    calling into the CLR from managed code via QCall and FCall methods
  • 原文地址:https://www.cnblogs.com/xgao/p/4156097.html
Copyright © 2011-2022 走看看