.NET中JSON序列化(数据集转JSON)

Json序列化和反序列化指的是:对象序列化为JSON,并可用于从 JSON 反序列化对象

 .net 3.5中已支持JSON,引用命名空间:

using System.Web.Script.Serialization;

用其中:JavaScriptSerializer类进行操作,

public string ToJson(object o)

{

  JavaScriptSerializer servializer = new JavaScriptSerializer();

    return servializer.Serialize(o);

 }

 

json.ashx处理页面中,Code

class tempclass

    {

        private string _IP;

 

        public string IP

        {

            get { return _IP; }

            set { _IP = value; }

        }

        private string _country;

 

        public string Country1

        {

            get { return _country; }

            set { _country = value; }

        }

        private string _city;

 

        public string City1

        {

            get { return _city; }

            set { _city = value; }

        }

}

 

把数据库中数据至泛型集合中。。。。

List<tempclass> templist = new List<tempclass>();

                foreach (DataRow item in ds.Tables[0].Rows)

                {

                    templist.Add(new tempclass()

                    {

                        IP = item["IP4"].ToString(),

                        Country1 = item["country"].ToString(),

                        City1 = item["city"].ToString()

                    });

                }

 

System.Text.StringBuilder sb = new System.Text.StringBuilder();

   sb.Append("{");

   sb.Append("totalCount:");

   sb.Append(totalCount.ToString());

   sb.Append(",data:");

   sb.Append(ToJson(templist)); //序列化从数据库中读取的数据集

   sb.Append("}");

   context.Response.ContentType = "text/plain";

   context.Response.Write(sb.ToString());

   context.Response.End();

 

 或者用LinQ获取数据源就更为简单了:

var dslinq = from p in dss.Tables[0].AsEnumerable()

                             select new {

                               IP = p.Field<string>("IP4"),

                               country = p.Field<string>("country"),

                              city = p.Field<string>("city")

                 };

 

接下来就是客户端读取json数据并显示,这是用jQuery$.ajax实现:

 $(document).ready(function(){

   $.ajax({

     type:"POST",

     dataType:"json",

     url:"/json.ashx",

     success:function(msg){

       $.each(msg.data,function(i,item){

         $("<tr class='newrow'></tr>").append("<td>" + item.IP + "</td>" +

                 "<td>" + item.country + "</td>" +

                 "<td>" + item.city + "</td>").appendTo($("#List tbody"));

                });

              }

           }); 

显示结果如下:

 });

.NET中JSON序列化(数据集转JSON) - jalen - Jalen

 

 

 

posted @ 2014-03-03 17:10  随风任飘遥  阅读(2860)  评论(0)    收藏  举报
1、不要犯经验主义的错误,有些经验可能是错误的。 2、发现bug要及时处理,不可为了赶工而忽略。随机性出现的bug更要注意,因为这类bug更难发现,也就更能解决。