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