公共的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 ...
随机推荐
- Java从零开始学二十(集合简介)
一.为什么需要集合框架 数组的长度是固定的,但是如果写程序时并不知道程序运行时会需要多少对象.或者需要更复杂的方式存储对象,---那么,可以使用JAVA集合框架,来解决这类问题 二.集合框架主要接口 ...
- Web 前端攻防(2014版)-baidu ux前端研发部
http://fex.baidu.com/articles/page2/ Web 前端攻防(2014版) zjcqoo | 20 Jun 2014 禁止一切外链资源 外链会产生站外请求,因此可以被利用 ...
- Linux rpm 命令参数使用详解[介绍和应用]
RPM是RedHat Package Manager(RedHat软件包管理工具)类似Windows里面的“添加/删除程序” rpm 执行安装包二进制包(Binary)以及源代码包(Source)两种 ...
- java之八大排序
的关系: 1.直接插入排序 (1)基本思想:在要排序的一组数中,假设前面(n-1)[n>=2] 个数已经是排 好顺序的,现在要把第n个数插到前面的有序数中,使得这n个数 也是排好顺序的.如此反 ...
- vue provide和inject使用
provide和inject使用场景也是组件传值,尤其是祖父组件--孙组件等有跨度的组件间传值,单向传值(由provide的组件传递给inject的组件). provide 选项应该是一个对象或返回一 ...
- ORACLE-SQL(一)
迁移时间:2017年6月1日10:02:43 CreateTime--2017年6月1日09:59:30Author:Marydon 一.SQL语句 (一)基础篇 1.1.1 where 子句 1 ...
- 〖Linux〗打开qtcreater出现错误的解决方法
1. 更换了显卡驱动,发现打开qtcreater时出现了以下的错误: qtcreator: error : cannot open shared object file: No such file o ...
- Android 4 编程入门经典
这是一本入门级的经典教才从Android编程入门到发布Android应用程序,每一个章节都是讲得很透,让人轻松的接受. 第1章 Android编程入门 1.1 Android简介 1.1.1 Andr ...
- hdu 4412 Sky Soldiers(区间DP)
Sky Soldiers Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Tot ...
- 转发:消息发布时间展示为刚刚、几分钟前、几小时前等等(php篇)
一.思路解析区: 1.获取当前的时间: 2.获取发布的时间: 3.计算两个的时间差: 4.判断这个时间差的范围给出对应的结果: 二.代码展示区: function tranTime($time) { ...