using System.Web.Script.Serialization;

using System.Runtime.Serialization.Json;

    /// <summary>
    /// json格式序列化
    /// </summary>
    public class JsonList : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = System.Text.Encoding.UTF8;

            HttpRequest Request = context.Request;
            HttpResponse Response = context.Response;
            string action = Request.Form["action"];
            string OrderNum = context.Request["ordernum"];

            ArrayList tmp = new ArrayList();
            tmp.Add("{\"gName\":\"张三1\",\"description\":\"描述1\"}");
            tmp.Add("{\"gName\":\"张三2\",\"description\":\"描述2\"}");
            tmp.Add("{\"gName\":\"张三3\",\"description\":\"描述3\"}");
            tmp.Add("{\"gName\":\"张三4\",\"description\":\"描述4\"}");
            tmp.Add("{\"gName\":\"张三5\",\"description\":\"描述5\"}");
            tmp.Add("{\"gName\":\"张三6\",\"description\":\"描述6\"}");
            tmp.Add("{\"gName\":\"张三7\",\"description\":\"描述7\"}");
            tmp.Add("{\"gName\":\"张三8\",\"description\":\"描述8\"}");
            tmp.Add("{\"gName\":\"张三9\",\"description\":\"描述9\"}");
            tmp.Add("{\"gName\":\"张三10\",\"description\":\"描述10\"}");

            if (action == "one")
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                Employee emp = new Employee()
                {
                    gName = "梦之队",
                    description = "描述"
                };
                string jsonResult = "[" + js.Serialize(emp) + "]";
                context.Response.Write(jsonResult);
            }
            else if (action == "two")
            {
                Employee emp = new Employee();
                emp.gName = "方式二";
                emp.description = "描述";
                string jsonResult = "[" + this.JsonSerializa<Employee>(emp) + "]";
                context.Response.Write(jsonResult);
            }
            else if (action == "three")
            {
                /*用javaScriptSerializer来生成JSON数据*/
                var employees = new List<Employee>();
                employees.Add(new Employee
                {
                    gName = "张三方式三",
                    description = "描述1"
                });
                employees.Add(new Employee
                {
                    gName = "张三方式三",
                    description = "描述2"
                });
                JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
                var jsonResult = javaScriptSerializer.Serialize(employees);
                context.Response.Write(jsonResult);
            }
            else
            {
                string jsonResult = "[" + string.Join(",", (string[])tmp.ToArray(typeof(string))) + "]";
                context.Response.Write(jsonResult);
            }
        }

/// <summary>
        /// json序列号
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public string JsonSerializa<T>(T t)
        {
            DataContractJsonSerializer zer = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            zer.WriteObject(ms, t);
            string jsonstring = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonstring;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

    public class Employee
    {
        public string description { get; set; }

        public string gName { get; set; }
    }


方式一:

后台处理

[HttpPost]public JsonResult SendEmail(){int success = 0;int fail = 0;int count = Convert.ToInt32(Request.Form["countnum"]);for (int i = 0; i < count; i++){if (i % 2 == 0)success += 1;elsefail += 1;}JsonResult jsonResult = new JsonResult{Data = new{successCount = success,failCount = fail,}};return Json(jsonResult);}

前台输出

function OpenEmail1() {$.ajax({url: "/tblGroups/SendEmail",type: 'post',data: {countnum: $("#hidCount").val()},beforeSend: function () {$("#loading").show();},error: function () {alert("出错了");},success: function (data) {$("#lblSuccess").html(data.Data.successCount);$("#lblFail").html(data.Data.failCount);$("#loading").hide();$("#emailDIV").show();$("#fade").show();}});}

方式二:

后台代码:

[HttpPost]
public JsonResult GetModel(FormCollection collection)
{string Action = collection["action"].ToString();string strid = Request.Form["id"].ToString();Guid id = new Guid(strid);return Json(GetGroupsModel(id));
}/// <summary>
/// 返回一个实体
/// </summary>
/// <param name="gid">id</param>
/// <returns></returns>
private IEnumerable<tblGroups> GetGroupsModel(Guid gid)
{var query = from g in db.tblGroupswhere g.Id == gidselect new{Id = g.Id,Name = g.Name,Description = g.Description,SumCount = (from m in db.tblMemberswhere m.GroupId == g.Idselect m).Count()};return query.ToList().Select(C => new tblGroups{Id = C.Id,Name = C.Name,Description = C.Description,CountNum = C.SumCount});
}

前台代码:

function OpenWin(id) {$("#light").show();$("#fade").show();$.ajax({url: "/tblGroups/GetModel",type: 'post',data: {action: "GetModel",id: id},success: function (data) {for (var i = 0; i < data.length; i++) {$("#lblName").html(data[i].Name);$("#lblCount").html(data[i].CountNum);$("#hidCount").val(data[i].CountNum);}}});
}

结果集是object类型循环输出

function sel() {$.ajax({url: "/Trace/select",type: "post",data: {name: $("#selBatch").val()},success: function (data) {var objs = data;var str = "";$("#tbd").html("");for (var n in objs){str += "<tr>";str += "<td>" + objs[n].BatchID + "</td>";str += "<td>" + objs[n].Path + "</td>";str += "</tr>";}$("#tbd").html(str);}});
}

Ajax请求

function InitData(pageindx, ofile, otype) {
$.ajax({url: '/Campaign/Ajax_Read',  //请求地址type: 'POST',                //请求方法dataType: 'json',            //返回数据类型(json,xml,html)data: {                      //传递参数action: 'paging',pagenum: pageindx,orderFile: ofile,orderType: otype},beforeSend: function () {    //发送请求前$("#loading").show();},error: function () {         //出现错误时提示状态alert("出错了");},complete: function() {       //请求完成后alert("请求完成后提示信息")},success: function(data) {    //请求成功时返回数据var objs = jQuery.parseJSON(data);for (var i = 0; i < objs.length; i++) {$("#lblSuccess").html(objs[i].successCount);$("#lblFail").html(objs[i].failCount);}}})
}

async设置异步同步并设置数组

function createRandomData() {$.ajax({url: '/Handler/JsonList.ashx',type: 'POST',async: false,data: {action: ''},success: function(responseText) {var re = responseText.toJson();var data123 = [];$.each(re, function(i, n) {data123.push({Id: i + 1,GroupName: n.gName,Description: n.description,Member: n.member,Email: n.email});});}});
}

方式三

后台代码

DataSet ds = DbHelperSQL.Query(sql.ToString());ArrayList tmp = new ArrayList();for (int i = 0; i < ds.Tables[0].Rows.Count; i++){tmp.Add("{Times:" + ds.Tables[0].Rows[i]["Times"] + "," +"Totals:" + ds.Tables[0].Rows[i]["Totals"] + "," +"Drinking:" + ds.Tables[0].Rows[i]["Drinking"] + "," +"Surplus:" + ds.Tables[0].Rows[i]["Surplus"] + "}");}string jsonResult = "[" + string.Join(",", (string[])tmp.ToArray(typeof(string))) + "]";return jsonResult;

前台代码

$.ajax({async: false,url: "@Url.Action("GetModel", "BarChart")",type: 'post',data: {name: name,area: area,begin: begin,end: end},success: function (data) {var objs = eval(data);for (var i = 0; i < objs.length; i++) {dataTime.push(objs[i].Times);dataDrinking.push(objs[i].Drinking);dataSurplus.push(objs[i].Surplus);}}});

后台object循环输出

ResultMessage<object> result = new ResultMessage<object>();
result = busi.GetListBatch();
string[] arr = result.Data as string[];
List<SelectListItem> select1 = new List<SelectListItem>();
select1.Add(new SelectListItem { Text = "请选择...", Value = "" });
for (int i = 0; i < arr.Length; i++)
{select1.Add(new SelectListItem{Text = arr[i].ToString(),Value = arr[i].ToString()});
}

.Net Json格式序列化相关推荐

  1. 数据传输:json格式序列化与反序列化(将类转化为json格式与将json格式转化为类)

    数据传输:json格式序列化与反序列化(将类转化为json格式与将json格式转化为类) 在最近的实验中,使用了json来传送客户端与服务端的信息,之前原本想使用自己定义的格式,但是使用json可以将 ...

  2. 利用cJSON解析JSON格式

    目录 一.JSON格式 二.cJSON下载 三.cJSON常用函数接口 四.cJSON解析JSON案例 1.一层键值 2.多层键值(两次为例) 3.json数组解析 五.JSON添加数据 (与链表类似 ...

  3. java中的json_Java中Json格式总结

    Java中Json格式总结 JSON(JavaScript Object Notation) 是一种轻量级的基于文本的数据交换格式.它采用完全独立于语言的文本格式,易于读写同时也易于机器解析和生成(网 ...

  4. 步步为营:Asp.Net序列化Json格式的两种方法

    过去我们使用JSON.net序列化一个对象,在asp.net3.5中已经集成了序列化对象为json的方法. 我们分别针对System.Runtime.Serialization.Json和System ...

  5. 字定义JSON序列化支持datetime格式序列化

    字定义JSON序列化支持datetime格式序列化 由于json.dumps无法处理datetime日期,所以可以通过自定义处理器来做扩展,如: import json from datetime i ...

  6. python 日志输出为json格式文件_Py修行路 python基础 (二十一)logging日志模块 json序列化 正则表达式(re)...

    一.日志模块 两种配置方式:1.config函数 2.logger #1.config函数 不能输出到屏幕 #2.logger对象 (获取别人的信息,需要两个数据流:文件流和屏幕流需要将数据从两个数据 ...

  7. Ajax 发送json格式数据以及发送文件(FormData)和自带的序列化组件: serializers

    前后端传输数据的编码格式(contentType) get请求数据就是直接放在url?后面的 url?usernmae=junjie&password=123... 可以向后端发送post请求 ...

  8. Json的序列化和反序列化

    1.引用命名空间: using System.Runtime.Serialization; 2.json的序列化和反序列化的方法: publicclass JsonHelper { ///<su ...

  9. Spring Boot 无侵入式 实现 API 接口统一 JSON 格式返回

    点击上方蓝色"方志朋",选择"设为星标" 回复"666"获取独家整理的学习资料! 无侵入式 统一返回JSON格式 其实本没有没打算写这篇博客 ...

最新文章

  1. 九度 题目1044:Pre-Post
  2. 思考--为何早晨型人更容易成功
  3. [工具]-文件明文导出工具
  4. C++使用linked list(链表)实现circular queue(循环队列)(附完整源码)
  5. error 1307 (HY000):Failed to create procedure
  6. 基因组中的趣事(一):这个基因编码98种转录本
  7. linux 进程suricata,开源USM之IDS suricata
  8. 估算服务器处理数据性能,服务器性能计算方法-20210720074826.docx-原创力文档
  9. 力扣题目——637. 二叉树的层平均值
  10. 中铁总数据中心落户武清 项目总投资22.7亿元
  11. 上课解除教师机控制(红蜘蛛)超详细
  12. 游戏框架(Unity3D游戏客户端基础框架)
  13. 开源音乐软件——落雪
  14. SDRAM中的DQM
  15. OAuth 2.0 授权认证详解
  16. 生成对抗网络(六)----------Image Denoising Using a Generative Adversarial Network(用GAN对图像去噪)
  17. 小白面试新媒体运营岗位
  18. 城市“智慧发展”的核心是人性化
  19. 淘宝页面详情采集API调用展示(APP端商品详情)
  20. 【防火墙配置QOS之最小带宽保证】

热门文章

  1. 百问网七天物联网课程(第二天)
  2. 百问网七天物联网课程笔记(第七天)
  3. 记一次MATLAB/Simulink的光伏板仿真试手
  4. 夏日优惠:United Plugins 推出 吉他效果器促销套装
  5. ifconfig不显示ip,虚拟机静态IP设置方法
  6. js中对象不支持此属性或方法
  7. 旋转不变性与旋转等变性
  8. 讲课系列——评价政策模型
  9. 项目install的时候报错gyp ERR! find Python
  10. 不会开赛车的管理者不是好的开发人