.NET下 JSON 的一些常用操作
1.JSON的序列化和反序列化
Newtonsoft.Json dll 下载地址http://json.codeplex.com/
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; namespace PlayJSON { class Program { static void Main( string [] args) { List<StuInfo> list = new List<StuInfo>() { new StuInfo{StuName= "张三" ,StuSex= "男" ,StuAge=11}, new StuInfo{StuName= "李四" ,StuSex= "男" ,StuAge=32}, new StuInfo{StuName= "王翠花" ,StuSex= "女" ,StuAge=64} }; string jsonStr = JavaScriptConvert.SerializeObject(list); //将对象转换成json存储 Console.WriteLine( "JSON字符串" +jsonStr); Console.ReadLine(); List<StuInfo> newList = new List<StuInfo>(); newList = (List<StuInfo>)JavaScriptConvert.DeserializeObject(jsonStr, typeof (List<StuInfo>)); //反序列化 //StuInfo s = new StuInfo() { StuName = "阿龙", StuSex = "男", StuAge = 33 }; //string sigleJSON = JavaScriptConvert.SerializeObject(s); //StuInfo newS = (StuInfo)JavaScriptConvert.DeserializeObject(sigleJSON); //Console.WriteLine("姓名:" + newS.StuName + "---性别:" + newS.StuSex + "--年龄:" + newS.StuAge + "\n\n"); foreach (StuInfo item in newList) { Console.WriteLine( "姓名:" + item.StuName + "---性别:" + item.StuSex + "--年龄:" + item.StuAge + "\n\n" ); } Console.ReadLine(); } } public class StuInfo { public string StuName { set ; get ; } public string StuSex { set ; get ; } public int StuAge { set ; get ; } } } |
|
2.在web中
/// <summary> /// Handler1 的摘要说明 /// </summary> public class Handler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json" ; List<StuInfo> list = new List<StuInfo>() { new StuInfo{StuName= "张三" ,StuSex= "男" ,StuAge=11}, new StuInfo{StuName= "李四" ,StuSex= "男" ,StuAge=32}, new StuInfo{StuName= "王翠花" ,StuSex= "女" ,StuAge=64} }; string jsonStr = JavaScriptConvert.SerializeObject(list); context.Response.Write(jsonStr); context.Response.End(); } public bool IsReusable { get { return false ; } } } public class StuInfo { public string StuName { set ; get ; } public string StuSex { set ; get ; } public int StuAge { set ; get ; } } |
前台页面上的调用:这里采用jquery 的ajax请求
<head runat="server"> <title>JSON</title> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { $("#btnOK").click(function () { $.ajax({ type: "JSON", url: "Handler1.ashx", data: null, success: function (msg) { var con=""; for (var i = 0; i < msg.length; i++) { con += "姓名:" + msg[i].StuName + "--性别:" + msg[i].StuSex + "--" + "--年龄:" + msg[i].StuAge+"<br/>"; } $("#divContent").html("长度:" + msg.length + "--具体内容:<br/>" + con); } }); }); }); </script> </head> <body> <form id="form1" runat="server"> <div> <input type="button" id="btnOK" value="点我获得JSON数据" /> <div id="divContent"></div> </div> </form> </body>
现在经常会用到json,因此经常会需要对其进行序列化和反序列化。,.NET Framewok 3.5也提供了JSON对象序列化和反序列化的类,这就是System.Runtime.Serialization.Json 命名空间下的 DataContractJsonSerializer 类。利用这个类,可以实现JSON对象的序列化和反序列化。
现在我提供一个类JSON对象序列化和反序列化的类供参考用:
/// <summary> /// JSON帮助类。用于将对象转换为Json格式的字符串,或者将Json的字符串转化为对象。 /// </summary> public static class JsonHelper { /// <summary> /// 将对象转化为Json字符串 /// </summary> /// <typeparam name="T">源类型</typeparam> /// <param name="obj">源类型实例</param> /// <returns>Json字符串</returns> public static string GetJsonFromObj<T>(T obj) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream ms = new MemoryStream()) { jsonSerializer.WriteObject(ms, obj); return Encoding.UTF8.GetString(ms.ToArray()); } } /// <summary> /// 将Json字符串转化为对象 /// </summary> /// <typeparam name="T">目标类型</typeparam> /// <param name="strJson">Json字符串</param> /// <returns>目标类型的一个实例</returns> public static T GetObjFromJson<T>( string strJson) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson))) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(obj.GetType()); return (T)jsonSerializer.ReadObject(ms); } } /// <summary> /// 将DataTable转换为JSON字符串 /// </summary> /// <param name="dt">数据表</param> /// <returns>JSON字符串</returns> public static string GetJsonFromDataTable(DataTable dt) { StringBuilder JsonString = new StringBuilder(); if (dt != null && dt.Rows.Count > 0) { JsonString.Append( "{ " ); JsonString.Append( "\"TableInfo\":[ " ); for ( int i = 0; i < dt.Rows.Count; i++) { JsonString.Append( "{ " ); for ( int j = 0; j < dt.Columns.Count; j++) { if (j < dt.Columns.Count - 1) { JsonString.Append( "\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"," ); } else if (j == dt.Columns.Count - 1) { JsonString.Append( "\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\"" ); } } if (i == dt.Rows.Count - 1) { JsonString.Append( "} " ); } else { JsonString.Append( "}, " ); } } JsonString.Append( "]}" ); return JsonString.ToString(); } else { return null ; } } /// <summary> /// 将对象转化为Json字符串 /// </summary> /// <param name="obj">源对象</param> /// <returns>json数据</returns> public static string ObjToJson( this object obj) { JavaScriptSerializer serialize = new JavaScriptSerializer(); return serialize.Serialize(obj); } /// <summary> /// 将Json字符串转化为对象 /// </summary> /// <param name="strJson">Json字符串</param> /// <returns>目标对象</returns> public static T JsonToObj<T>( string strJson) { JavaScriptSerializer serialize = new JavaScriptSerializer(); return serialize.Deserialize<T>(strJson); } /// <summary> /// 将对象转化为Json字符串(控制深度 ) /// </summary> /// <param name="obj">源对象</param> /// <param name="recursionDepth">深度</param> /// <returns>json数据</returns> public static string ObjToJson( this object obj, int recursionDepth) { JavaScriptSerializer serialize = new JavaScriptSerializer(); serialize.RecursionLimit = recursionDepth; return serialize.Serialize(obj); } /// <summary> /// 将Json字符串转化为对象(控制深度 ) /// </summary> /// <param name="strJson">Json字符串</param> /// <param name="recursionDepth">深度</param> /// <returns>目标对象</returns> public static T JsonToObj<T>( string strJson, int recursionDepth) { JavaScriptSerializer serialize = new JavaScriptSerializer(); serialize.RecursionLimit = recursionDepth; return serialize.Deserialize<T>(strJson); } /// <summary> /// 将DataTable转换为JSON字符串 /// </summary> /// <param name="dt">DataTable</param> /// <returns>json数据</returns> public static string DataTableToJson(DataTable dt) { Dictionary< string , object > dic = new Dictionary< string , object >(); int index = 0; foreach (DataRow dr in dt.Rows) { Dictionary< string , object > result = new Dictionary< string , object >(); foreach (DataColumn dc in dt.Columns) { result.Add(dc.ColumnName, dr[dc].ToString()); } dic.Add(index.ToString(), result); index++; } return ObjToJson(dic); } } |
使用如下:
按 Ctrl+C 复制代码
按 Ctrl+C 复制代码