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;