public 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); }///第二种方法
public class ConvertJson
{ #region 私有方法
/// <summary> /// 过滤特殊字符 /// </summary>
private static string String2Json(String s)
{ StringBuilder sb = new StringBuilder();
for (int i = 0; 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;
default:
sb.Append(c); break;
}
}
return sb.ToString();
}
/// <summary> /// 格式化字符型、日期型、布尔型 /// </summary>
private static string StringFormat(object value, Type type)
{ string str=string.Empty;
if (value == null || value.ToString()=="")
{ str = "\"\"";
}
else if (type == typeof(string))
{ str = String2Json(value.ToString());
str = "\"" + str + "\"";
}
else if (type == typeof(DateTime?) || type == typeof(DateTime) || type == typeof(Guid) || type == typeof(TimeSpan))
{ str = "\"" + value.ToString() + "\"";
}
else if (type == typeof(bool))
{ str = value.ToString().ToLower();
}
else //一般为数字类型的
{
str = value.ToString();
}
return str;
}
#endregion
#region List转换成Json /// <summary> /// List转换成Json /// </summary>
public static string ObjectToJson(object obj) {
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, obj);
byte[] dataBytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(dataBytes, 0, (int)stream.Length);
return Encoding.UTF8.GetString(dataBytes);
}
public static string ToJson<T>(IList<T> list)
{ StringBuilder Json = new StringBuilder();
Json.Append("[");
for (int i = 0; i < list.Count; i++)
{ T obj = list[i];
Json.Append(ToJson(obj));
Json.Append(",");
}
if (Json.Length > 1)//如果长度大于1,那么移除最后一个逗号,如果长度不大于1,那么内容应该为"[",如果移除了,那么就不能和后面的"]"形成闭合了 韩树河 2012.8.15
{
Json.Remove(Json.Length - 1, 1);
}
Json.Append("]");
return Json.ToString();
}
/// <summary> /// List转换成Json /// </summary>
public static string ListToJson<T>(IList<T> list, string jsonName)
{ StringBuilder Json = new StringBuilder();
if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
Json.Append("{\"" + jsonName + "\":");
Json.Append(ToJson(list));
Json.Append("}");
return Json.ToString();
}
#endregion
#region 对象转换为Json
/// <summary> /// 对象转换为Json /// </summary>
/// <param name="jsonObject">对象</param> /// <returns>Json字符串</returns>
public static string ToJson(object jsonObject)
{
string Json = "{";
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
for (int i = 0; i < propertyInfo.Length; i++)
{
object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
Type type=propertyInfo[i].PropertyType;
string value = string.Empty;
value = StringFormat(objectValue,type);
Json += "\"" + String2Json(propertyInfo[i].Name) + "\":" + value + ",";
}
Json = StringPlus.DelLastChar(Json, ",");
return Json + "}";
} #endregion
#region 对象集合转换Json /// <summary> /// 对象集合转换Json /// </summary>
/// <param name="array">集合对象</param>
/// <returns>Json字符串</returns>
public static string ToJson(IEnumerable array)
{ string Json = "[";
foreach (object item in array)
{ Json += ToJson(item) + ",";
}
Json.Remove(Json.Length - 1, Json.Length);
return Json + "]";
} #endregion
#region 普通集合转换Json /// <summary> /// 普通集合转换Json /// </summary> /// <param name="array">集合对象</param> /// <returns>Json字符串</returns> public static string ToArrayString(IEnumerable array) { string Json = "["; foreach (object item in array) { Json = ToJson(item.ToString()) + ","; } Json.Remove(Json.Length - 1, Json.Length); return Json + "]"; } #endregion
#region DataSet转换为Json /// <summary> /// DataSet转换为Json /// </summary> /// <param name="dataSet">DataSet对象</param> /// <returns>Json字符串</returns> public static string ToJson(DataSet dataSet) { string Json = "{"; foreach (DataTable table in dataSet.Tables) { Json += "\"" + table.TableName + "\":" + ToJson(table) + ","; } Json = Json.TrimEnd(','); return Json + "}"; } #endregion
#region Datatable转换为Json /// <summary> /// Datatable转换为Json /// </summary> /// <param name="table">Datatable对象</param> /// <returns>Json字符串</returns> public static string ToJson(DataTable dt) { StringBuilder Json = new StringBuilder(); Json.Append("["); DataRowCollection drc = dt.Rows; for (int i = 0; i < drc.Count; i++) { Json.Append("{"); for (int j = 0; j < dt.Columns.Count; j++) { string strKey = dt.Columns[j].ColumnName; object strValue = drc[i][j]; Type type = dt.Columns[j].DataType; Json.Append("\"" + strKey + "\":"); strValue = StringFormat(strValue, type); if (j < dt.Columns.Count - 1) { Json.Append(strValue + ","); } else { Json.Append(strValue); } } Json.Append("},"); } if (Json.Length > 1)//如果长度大于1,那么移除最后一个逗号,如果长度不大于1,那么内容应该为"[",如果移除了,那么就不能和后面的"]"形成闭合了 韩树河 2012.8.15 { Json.Remove(Json.Length - 1, 1); } Json.Append("]"); return Json.ToString(); }
/// <summary> /// DataTable转换为Json /// </summary> public static string ToJson(DataTable dt, string jsonName) { StringBuilder Json = new StringBuilder(); if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName; Json.Append("{\"" + jsonName + "\":"); Json.Append(ToJson(dt)); Json.Append("}"); return Json.ToString(); } #endregion
#region DataReader转换为Json /// <summary> /// DataReader转换为Json /// </summary> /// <param name="dataReader">DataReader对象</param> /// <returns>Json字符串</returns> public static string ToJson(DbDataReader dataReader) { StringBuilder Json = new StringBuilder(); Json.Append("["); while (dataReader.Read()) { Json.Append("{"); for (int i = 0; i < dataReader.FieldCount; i++) { Type type = dataReader.GetFieldType(i); string strKey = dataReader.GetName(i); string strValue = dataReader[i].ToString(); Json.Append("\"" + strKey + "\":"); strValue = StringFormat(strValue, type); if (i < dataReader.FieldCount - 1) { Json.Append(strValue + ","); } else { Json.Append(strValue); } } Json.Append("},"); } dataReader.Close(); Json.Remove(Json.Length - 1, 1); Json.Append("]"); return Json.ToString(); } /// <summary> /// 格式化EASYUI DATAGRID JSON /// </summary> /// <param name="recordcount">总记录数</param> /// <param name="datatable">数据表</param> /// <returns></returns> public static string FormatJSONForEasyuiDataGrid(int recordcount, DataTable datatable) { string s = "{\"total\":" + recordcount.ToString() + ",\"rows\":" + Common.ConvertJson.ToJson(datatable) + "}"; return s; } public static string FormatJSONForEasyuiDataGrid<T>(int recordcount, IList<T> list) { string s = "{\"total\":" + recordcount.ToString() + ",\"rows\":" + Common.ConvertJson.ToJson(list) + "}"; return s; } #endregion }