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"));
});
}
});
顯示結果如下:
});
