首页 > 代码库 > JsonHelper
JsonHelper
public class JsonHelper { /// <summary> /// 。net对象序列化为Json对象 /// </summary> /// <typeparam name="T">。net对象类型</typeparam> /// <param name="obj">需要序列化的。net对象</param> /// <returns>Json对象</returns> public static string ToJson<T>(T obj) { System.Web.Script.Serialization.JavaScriptSerializer script = new System.Web.Script.Serialization.JavaScriptSerializer(); return script.Serialize(obj); } /// <summary> /// 反序列化Json对象 /// </summary> /// <typeparam name="T">需要转换成的对象</typeparam> /// <param name="sJson">Json串</param> /// <returns>。net对象</returns> public static T Deserialize<T>( string sJson) where T : class { System.Web.Script.Serialization.JavaScriptSerializer script = new System.Web.Script.Serialization.JavaScriptSerializer(); return script.Deserialize<T>(sJson); } /// <summary> /// List数组对象序列化 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="obj">List对象值</param> /// <returns>Json串</returns> public static String ToString<T>(List<T> obj) { string str = string .Empty; foreach ( object o in obj) { str = str + o.ToString() + "\r\n" ; } return str; } // 将datatable转换为json public static string Dtb2Json(DataTable dtb) { System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer(); System.Collections.ArrayList dic = new System.Collections.ArrayList(); foreach (DataRow dr in dtb.Rows) { System.Collections.Generic.Dictionary< string , object > drow = new System.Collections.Generic.Dictionary< string , object >(); foreach (DataColumn dc in dtb.Columns) { drow.Add(dc.ColumnName, dr[dc.ColumnName]); } dic.Add(drow); } //序列化 return jss.Serialize(dic); } /// <summary> /// Model 转换为Json /// </summary> /// <typeparam name="T">数据类型</typeparam> /// <param name="obj">数据对象</param> /// <returns></returns> public static string ObjectToJson<T>(T o) { StringBuilder Json = new StringBuilder(); T obj = Activator.CreateInstance<T>(); Type type = obj.GetType(); PropertyInfo[] Pi = type.GetProperties(); Json.Append( "{" ); for ( int i = 0; i < Pi.Length; i++) { Json.Append( "\"" + Pi[i].Name.ToString() + "\":\"" + ChangeString(StringHelper.SetString(Pi[i].GetValue(o, null ))) + "\"" ); if (i < Pi.Length - 1) { Json.Append( "," ); } } Json.Append( "}" ); return Json.ToString(); } /// <summary> /// 把含有html标签的元素进行转换 /// </summary> /// <param name="str"></param> /// <returns></returns> private static string ChangeString( string str) { //str含有HTML标签的文本 str = str.Replace( "<" , "<" ); str = str.Replace( ">" , ">" ); str = str.Replace( " " , " " ); str = str.Replace( "\n" , "<br>" ); str = str.Replace( "&" , "&" ); return str; } } |
JsonHelper
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。