公共的Json操作C#类
using System;
using System.Data;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
using System.Data.Common;
using System.Collections;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Json; namespace System.Common
{
public static class Json
{
/// <summary>
/// List转成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonName"></param>
/// <param name="list"></param>
/// <returns></returns>
public static string ListToJson<T>(IList<T> list, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName))
jsonName = list[].GetType().Name;
Json.Append("{\"" + jsonName + "\":[");
if (list.Count > )
{
for (int i = ; i < list.Count; i++)
{
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
Json.Append("{");
for (int j = ; j < pi.Length; j++)
{
Type type;
object o = pi[j].GetValue(list[i], null);
string v = string.Empty;
if (o != null)
{
type = o.GetType();
v = o.ToString();
}
else
{
type = typeof(string);
} Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(v, type)); if (j < pi.Length - )
{
Json.Append(",");
}
}
Json.Append("}");
if (i < list.Count - )
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
} /// <summary>
/// 序列化集合对象
/// </summary>
public static string JsonSerializerByArrayData<T>(T[] tArray)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T[]));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, tArray);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
string p = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
} /// <summary>
/// 序列化单个对象
/// </summary>
public static string JsonSerializerBySingleData<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
string p = @"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
} /// <summary>
/// 反序列化单个对象
/// </summary>
public static T JsonDeserializeBySingleData<T>(string jsonString)
{
//将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
} /// <summary>
/// 反序列化集合对象
/// </summary>
public static T[] JsonDeserializeByArrayData<T>(string jsonString)
{
//将"yyyy-MM-dd HH:mm:ss"格式的字符串转为"\/Date(1294499956278+0800)\/"格式
string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T[]));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T[] arrayObj = (T[])ser.ReadObject(ms);
return arrayObj;
} /// <summary>
/// 将Json序列化的时间由/Date(1294499956278+0800)转为字符串
/// </summary>
private static string ConvertJsonDateToDateString(Match m)
{
string result = string.Empty;
DateTime dt = new DateTime(, , );
dt = dt.AddMilliseconds(long.Parse(m.Groups[].Value));
dt = dt.ToLocalTime();
result = dt.ToString("yyyy-MM-dd HH:mm:ss");
return result;
} /// <summary>
/// 将时间字符串转为Json时间
/// </summary>
private static string ConvertDateStringToJsonDate(Match m)
{
string result = string.Empty;
DateTime dt = DateTime.Parse(m.Groups[].Value);
dt = dt.ToUniversalTime();
TimeSpan ts = dt - DateTime.Parse("1970-01-01");
result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);
return result;
} /// <summary>
/// List转成json
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static string ListToJson<T>(IList<T> list)
{
object obj = list[];
return ListToJson<T>(list, obj.GetType().Name);
} /// <summary>
/// 对象转换为Json字符串
/// </summary>
/// <param name="jsonObject">对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(object jsonObject)
{
try
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("{");
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
for (int i = ; i < propertyInfo.Length; i++)
{
object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
if (objectValue == null)
{
continue;
}
StringBuilder value = new StringBuilder();
if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
{
value.Append("\"" + objectValue.ToString() + "\"");
}
else if (objectValue is string)
{
value.Append("\"" + objectValue.ToString() + "\"");
}
else if (objectValue is IEnumerable)
{
value.Append(ToJson((IEnumerable)objectValue));
}
else
{
value.Append("\"" + objectValue.ToString() + "\"");
}
jsonString.Append("\"" + propertyInfo[i].Name + "\":" + value + ","); ;
}
return jsonString.ToString().TrimEnd(',') + "}";
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// 对象集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString += ToJson(item) + ",";
}
if (jsonString.Length > )
{
jsonString.Remove(jsonString.Length - , jsonString.Length);
}
else
{
jsonString = "[]";
}
return jsonString + "]";
} /// <summary>
/// 普通集合转换Json
/// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToArrayString(IEnumerable array)
{
string jsonString = "[";
foreach (object item in array)
{
jsonString = ToJson(item.ToString()) + ",";
}
jsonString.Remove(jsonString.Length - , jsonString.Length);
return jsonString + "]";
} /// <summary>
/// Datatable转换为Json
/// </summary>
/// <param name="table">Datatable对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataTable dt)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = ; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = ; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
string strValue = drc[i][j].ToString();
Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (j < dt.Columns.Count - )
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - , );
jsonString.Append("]");
if (jsonString.Length == )
{
return "[]";
}
return jsonString.ToString();
} /// <summary>
/// DataTable转成Json
/// </summary>
/// <param name="jsonName"></param>
/// <param name="dt"></param>
/// <returns></returns>
public static string ToJson(DataTable dt, string jsonName)
{
StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName))
jsonName = dt.TableName;
Json.Append("{\"" + jsonName + "\":[");
if (dt.Rows.Count > )
{
for (int i = ; i < dt.Rows.Count; i++)
{
Json.Append("{");
for (int j = ; j < dt.Columns.Count; j++)
{
Type type = dt.Rows[i][j].GetType();
Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j] is DBNull ? string.Empty : dt.Rows[i][j].ToString(), type));
if (j < dt.Columns.Count - )
{
Json.Append(",");
}
}
Json.Append("}");
if (i < dt.Rows.Count - )
{
Json.Append(",");
}
}
}
Json.Append("]}");
return Json.ToString();
} /// <summary>
/// DataReader转换为Json
/// </summary>
/// <param name="dataReader">DataReader对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IDataReader dataReader)
{
try
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("["); while (dataReader.Read())
{
jsonString.Append("{");
for (int i = ; i < dataReader.FieldCount; i++)
{
Type type = dataReader.GetFieldType(i);
string strKey = dataReader.GetName(i);
string strValue = dataReader[i].ToString();
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (i < dataReader.FieldCount - )
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
if (!dataReader.IsClosed)
{
dataReader.Close();
}
jsonString.Remove(jsonString.Length - , );
jsonString.Append("]");
if (jsonString.Length == )
{
return "[]";
}
return jsonString.ToString();
}
catch (Exception ex)
{
throw ex;
}
} /// <summary>
/// DataSet转换为Json
/// </summary>
/// <param name="dataSet">DataSet对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(DataSet dataSet)
{
string jsonString = "{";
foreach (DataTable table in dataSet.Tables)
{
jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
}
jsonString = jsonString.TrimEnd(',');
return jsonString + "}";
} /// <summary>
/// 过滤特殊字符
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static string String2Json(String s)
{
StringBuilder sb = new StringBuilder();
for (int i = ; i < s.Length; i++)
{
char c = s.ToCharArray()[i];
switch (c)
{
case '\"':
sb.Append("\\\""); break;
case '\\':
sb.Append("\\\\"); break;
case '/':
sb.Append("\\/"); break;
case '\b':
sb.Append("\\b"); break;
case '\f':
sb.Append("\\f"); break;
case '\n':
sb.Append("\\n"); break;
case '\r':
sb.Append("\\r"); break;
case '\t':
sb.Append("\\t"); break;
case '\v':
sb.Append("\\v"); break;
case '\0':
sb.Append("\\0"); break;
default:
sb.Append(c); break;
}
}
return sb.ToString();
} /// <summary>
/// 格式化字符型、日期型、布尔型
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
private static string StringFormat(string str, Type type)
{
if (type != typeof(string) && string.IsNullOrEmpty(str))
{
str = "\"" + str + "\"";
}
else if (type == typeof(string))
{
str = String2Json(str);
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
else if (type == typeof(byte[]))
{
str = "\"" + str + "\"";
}else if(type==typeof(Guid))
{
str = "\"" + str + "\"";
}
return str;
} public static void RegistAjax(HtmlHead Header, Type type)
{
string assemblyName = type.FullName + "," + type.Assembly.FullName.Substring(, type.Assembly.FullName.IndexOf(","));
if (type.Assembly.FullName.StartsWith("App_Code."))
{
assemblyName = type.FullName + ",App_Code";
}
Literal l = new Literal();
l.Text = "\n<script type=\"text/javascript\" src=\"/ajaxpro/prototype.ashx\"></script>\n"
+ "<script type=\"text/javascript\" src=\"/ajaxpro/core.ashx\"></script>\n"
+ "<script type=\"text/javascript\" src=\"/ajaxpro/converter.ashx\"></script>\n"
+ "<script type=\"text/javascript\" src=\"/ajaxpro/" + assemblyName + ".ashx\"></script>\n";
Header.Controls.Add(l);
}
}
}
公共的Json操作C#类的更多相关文章
- C#工具类:Json操作帮助类(转载)
原文转载自C#工具类:Json操作帮助类_IT技术小趣屋. Json序列化和反序列化在程序开发中时常会遇到,在C#中可以使用很多种方法实现对数据的Json序列化和反序列化,封装一个Json操作工具类来 ...
- 【转载】C#工具类:Json操作帮助类
Json序列化和反序列化在程序开发中时常会遇到,在C#中可以使用很多种方法实现对数据的Json序列化和反序列化,封装一个Json操作工具类来简化相应的操作,该工具类中包含以下功能:对象转JSON.数据 ...
- 公共的Json操作类
using System; using System.Data; using System.Text; using System.Collections.Generic; using System.R ...
- JACKSON JSON 操作帮助类
一. 引入POM <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-li ...
- 【C#公共帮助类】JsonHelper 操作帮助类, 以后再也不用满地找Json了,拿来直接用
四个主要操作类:JsonConverter .JsonHelper .JsonSplit .AjaxResult 一.JsonConverter: 自定义查询对象转换动态类.object动态类转换j ...
- 【C#公共帮助类】JsonHelper 操作帮助类
四个主要操作类:JsonConverter .JsonHelper .JsonSplit .AjaxResult 一.JsonConverter: 自定义查询对象转换动态类.object动态类转换js ...
- ASP.NET2.0 Newtonsoft.Json 操作类分享
JSON 是现在比较流行的数据交互格式,NET3.0+有自带类处理JSON,2.0的话需要借助Newtonsoft.Json来完成,不然自己写的话,很麻烦. 网上搜索下载 Newtonsoft.Jso ...
- JWT(JSON Web Tokens)操作帮助类
载荷实体: /// <summary> /// JWT载荷实体 /// </summary> public sealed class JWTPlayloadInfo { /// ...
- Redis 操作帮助类
首先从Nuget中添加StackExchange.Redis包 1.Redis连接对象管理帮助类 using Mvc.Base; using Mvc.Base.Log; using StackExch ...
随机推荐
- 选择合适的Linux版本
以下纯属个人想法:欢迎指正 1.Linux桌面系统,首选Ubuntu.当然Ubuntu也有服务器版本,不建议使用 2.服务端的Linux稳定的服务器系统,在企业中从事运维工作Redhat或者CentO ...
- Oracle常用标准表
一.INV(库存) 子库存:mtl_secondary_inventories 事物处理:mtl_material_transactions mmt 事务处理来源类型:mtl_txn_source_t ...
- java开发工具之myeclipse调优
-vmargs -Xms512m //堆的最小值-Xmx512m //堆的最大值(两者设置相同,避免运行时的自动扩张)-XX:PermSize=256m //永久代的最小值 -XX:MaxPermSi ...
- Loadrunner脚本编程(1)-大体思路
http://www.360doc.com/content/10/0806/13/1698198_44076570.shtml 就目前的了解.Loadrunner的脚本语言其实和C没什么区别.他内部的 ...
- VC2012编译CEF3-转
原文地址:http://blog.csdn.net/tiplip/article/details/42047815 下载 代码下载:http://cefbuilds.com/,CEF 3.2556.1 ...
- Synchronized和Lock, 以及自旋锁 Spin Lock, Ticket Spin Lock, MCS Spin Lock, CLH Spin Lock
Synchronized和Lock synchronized是一个关键字, Lock是一个接口, 对应有多种实现. 使用synchronized进行同步和使用Lock进行同步的区别 使用synchro ...
- Java菜鸟入坑学习要点
一.掌握静态方法和属性 静态方法和属性用于描述某一类对象群体的特征,而不是单个对象的特征.Java中大量应用了静态方法和属性,这是一个通常的技巧.但是这种技巧在很多语言中不被频繁地使用.理解静态方法和 ...
- HDUOJ----4504 威威猫系列故事——篮球梦
威威猫系列故事——篮球梦 Time Limit: 300/100 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Total ...
- javascript高级程序设计第三章
看后总结: 1.区分大小写 2.标识符是有字母下划线$开头,并有字母.下划线.数字.美元符号组成. 3.建议用驼峰法命名标识符. 4.注释: 单行:// 多行: /* */ 5.严格模式: 在js ...
- 配置Windows server 2008文件同步[转]
众所周知,Linux系统可以用rsync来实现文件或目录的同步,windows系统下也一样可以.我们现在就用cwRsync来实现windows server 2008系统下的文件同步. 一.系统环境 ...