zoukankan      html  css  js  c++  java
  • json的序列化和反序列化

    后台把一个对象序列化发送到前台。注:不要序列化table,会有异常。应该是list或者字典

     PhotoBLL bll = new PhotoBLL();
            List<Photos> list =  bll.GetAllPhotos();
            
            //输出json格式的字符串
            JavaScriptSerializer jss = new JavaScriptSerializer();  //JavaScriptSerializer命名空间 using System.Web.Script.Serialization;
            string json = jss.Serialize(list);

            context.Response.Write(json);

    前端接收

    方法一:当前端是用$.getJson方式:

    $.getJSON("xxx.ashx, function (json) {

       for (var i = 0; i < json.length; i++) {

        var id = json[i].id;

        ...........

        })

    })

    方法二:当前端是用$.post/get方式:

    $.post("xxx.ashx?, function (data) {

       var json = eval(data);  //用eval解析json对象

       for (var i = 0; i < json.length; i++) {

          var id = json[i].id;

          ...........

          })

    })

    前端用js拼json发送到后台,并反序列化获取数据

    比如前端格式:

     var data = { "photo": "{"PTitle":"" + title + "","PUrl":"" + url + "","PTypeId":1,"PUserId":1,"PDes":""}","type":1 };//斜杠是转义。别写错

     $.ajax({
                    url: '/ashx/Enqeiry/ItemCode.ashx',
                    data: { "Enquiry": jsonTemp },  //serialize  data
                    async: false,
                    type: 'post',
                    success: function (msg) {
                        if (msg == "ok") {
                            try {
                                opener.location.reload(); //刷新父页面
                            } catch (e) {

                            }
                        }
                    },
                    error: function () { }
                });

    后台接收并反序列化

        string type = context.Request.Form["type"];
            // {"PTitle":"","PUrl":"","PTypeId":1,"PUserId":1,"PDes":""}
            string json = context.Request.Form["photo"];
            
            JavaScriptSerializer jss = new JavaScriptSerializer();
            //把json格式的字符串 转化成photos对象
            Photos photo = jss.Deserialize<Photos>(json);

  • 相关阅读:
    [No000068]document.body.clientHeight 和 document.documentElement.clientHeight 的区别
    [No000067]Js中获取当前页面的滚动条纵坐标位置scrollTop
    jquery 给a标签绑定click
    java 延时
    MySQL建表语句+添加注释
    ubuntu 搜狗输入法内存占用太多,卡顿不够处理办法
    org.apache.http.client.HttpClient使用方法
    json 文件打读取
    bootStrap @media 用法
    java web项目获取项目路径
  • 原文地址:https://www.cnblogs.com/nsky/p/3201596.html
Copyright © 2011-2022 走看看