zoukankan      html  css  js  c++  java
  • C#生成JSON数据

            protected void Page_Load(object sender, EventArgs e)
            {
                Response.Clear();
                Response.ContentType = "application/json;charset=utf-8";
    
                string str = "";
                DataSet ds = SqlHelper.GetSqlDataSet("select top 3 Staff_id,name_sc as Staff_name from [tbl_ac_info] where status='A'");
                
                List<tbl_ac_info> list = new List<tbl_ac_info>();
                foreach (DataRow item in ds.Tables[0].Rows)
                {
                    list.Add(new tbl_ac_info() { Staff_id = item[0].ToString(), Staff_name = item[1].ToString() });
                }
                str = ObjToJSON(list);
                Response.Write(str);
                Response.End();
            }
        [DataContract]
        [Serializable]
        public class tbl_ac_info
        {
            [DataMember]
            public string Staff_id { set; get; }
            [DataMember]
            public string Staff_name { set; get; }
    
        }
            /// <summary>
            /// 生成JSON字符
            /// </summary>
            /// <param name="obj">待生成的对象,如泛型实体</param>
            /// <returns></returns>
            protected string ObjToJSON(object obj)
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                Stream stream = new MemoryStream();
                serializer.WriteObject(stream, obj);
                stream.Position = 0;
                StreamReader streamReader = new StreamReader(stream);
                return streamReader.ReadToEnd();
            }
    <script type="text/javascript">
        $(function () {
            GetJSON();
        });
        function GetJSON() {
            $.getJSON("Ajax.aspx?action=export_app&n=" + Math.random(), { "div": "", "app_type": "formula" }, function (data) {
                $("#listStaff_id").html("<font color=green>数据加载中...</font>"); 
                if (data.length > 0) {
                    var list = "";
                    $.each(eval(data), function (index, json) {
                        list += json.Staff_id + " / " + json.Staff_name + "<br>";
                    });
                    $("#listStaff_id").html(list);
                }
                else {
                    $("#listStaff_id").html("没有记录");
                }
            });
        }
    </script>

    须引入命名空间:
    using System.Runtime.Serialization.Json;
    using System.ServiceModel.Web;

  • 相关阅读:
    零拷贝
    RxJava2源码解析
    一次博客崩溃日志分析
    Spring循环依赖的解决
    解决网络卡顿问题
    软工第一次作业
    3月26-27号训练笔记
    Codeforces Round #708 (Div. 2)题解A,B,C1,C2,E1,E2
    求出所有LIS的可行起点
    2020小米邀请赛决赛补题G,I,J(三DP)
  • 原文地址:https://www.cnblogs.com/myjacky/p/3557911.html
Copyright © 2011-2022 走看看