using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
public class DataToJson
{
/// <summary>
/// 把object对象序列化成json字符串
/// </summary>
/// <param name="obj">序列话的实例</param>
/// <returns>序列化json字符串</returns>
public static string SerializeToJson(object obj)
{
return JsonConvert.SerializeObject(obj);
}
/// <summary>
/// 把json字符串反序列化成Object对象
/// </summary>
/// <param name="json">json字符串</param>
/// <returns>对象实例</returns>
public static Object DeserializeFromJson(string json)
{
return JsonConvert.DeserializeObject(json);
}
/// <summary>
/// 把json字符串反序列化成泛型T
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="json">json字符串</param>
/// <returns>泛型T</returns>
public static T DeserializeFromJson<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json);
}
///<summary>
/// 返回easyui/extjs中datagrid使用的json格式
///</summary>
///<param name="dt">datatable数据</param>
///<param name="count">总的条数</param>
///<returns></returns>
public static string DataTableToJson(DataTable dt, int count)
{
StringBuilder sbjson = new StringBuilder();
sbjson.Append("{");
sbjson.Append("\"total\":" + count + ",\"rows\":[");
if (dt != null)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i > 0)
{
sbjson.Append(",");
sbjson.Append("{");
foreach (DataColumn dc in dt.Columns)
{
string value = StringPlus.HtmlEncode(dt.Rows[i][dc.ColumnName].ToString().Trim());
if (dt.Columns.IndexOf(dc) > 0)
{
sbjson.Append(",");
sbjson.Append("\"" + dc.ColumnName + "\":\"" + value + "\"");
}
else
{
sbjson.Append("\"" + dc.ColumnName + "\":\"" + value + "\"");
}
}
sbjson.Append("}");
}
else
{
sbjson.Append("{");
foreach (DataColumn dc in dt.Columns)
{
string value = StringPlus.HtmlEncode(dt.Rows[i][dc.ColumnName].ToString().Trim());
if (dt.Columns.IndexOf(dc) > 0)
{
sbjson.Append(",");
sbjson.Append("\"" + dc.ColumnName + "\":\"" + value + "\"");
}
else
{
sbjson.Append("\"" + dc.ColumnName + "\":\"" + value + "\"");
}
}
sbjson.Append("}");
}
}
}
sbjson.Append("]}");
return sbjson.ToString();
}
/// <summary>
/// 根据DataTable生成Json树结构
/// </summary>
/// <param name="tabel">数据源</param>
/// <param name="idCol">ID列</param>
/// <param name="txtCol">Text列</param>
/// <param name="rela">关系字段</param>
/// <param name="pId">父ID</param>
public static string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string rela, object pId)
{
string rlt = "";
StringBuilder result = new StringBuilder();
StringBuilder sb = new StringBuilder();
result.Append(sb.ToString());
sb.Length = 0;
if (tabel.Rows.Count > 0)
{
sb.Append("[");
string filer = string.Format("{0}=‘{1}‘", rela, pId);
DataRow[] rows = tabel.Select(filer);
if (rows.Length > 0)
{
foreach (DataRow row in rows)
{
sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"state\":\"open\"");
if (tabel.Select(string.Format("{0}=‘{1}‘", rela, row[idCol])).Length > 0)
{
sb.Append(",\"children\":");
GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol]);
result.Append(sb.ToString());
sb.Length = 0;
}
result.Append(sb.ToString());
sb.Length = 0;
sb.Append("},");
}
sb = sb.Remove(sb.Length - 1, 1);
}
sb.Append("]");
result.Append(sb.ToString());
rlt = result.ToString();
sb.Length = 0;
}
return rlt;
}
#region json转Datatable
/// <summary>
/// 根据Json返回DateTable,JSON数据格式如:
/// {table:[{column1:1,column2:2,column3:3},{column1:1,column2:2,column3:3}]}
/// </summary>
/// <param name="strJson">Json字符串</param>
/// <returns></returns>
public static DataTable JsonToDataTable(string strJson)
{
//取出表名
var rg = new Regex(@"(?<={)[^:]+(?=:\[)", RegexOptions.IgnoreCase);
string strName = rg.Match(strJson).Value;
DataTable tb = null;
//去除表名
strJson = strJson.Substring(strJson.IndexOf("[") + 1);
strJson = strJson.Substring(0, strJson.IndexOf("]"));
//获取数据
rg = new Regex(@"(?<={)[^}]+(?=})");
MatchCollection mc = rg.Matches(strJson);
for (int i = 0; i < mc.Count; i++)
{
string strRow = mc[i].Value;
string[] strRows = strRow.Split(‘,‘);
//创建表
if (tb == null)
{
tb = new DataTable();
tb.TableName = strName;
foreach (string str in strRows)
{
var dc = new DataColumn();
string[] strCell = str.Split(‘:‘);
dc.ColumnName = strCell[0];
tb.Columns.Add(dc);
}
tb.AcceptChanges();
}
//增加内容
DataRow dr = tb.NewRow();
for (int r = 0; r < strRows.Length; r++)
{
dr[r] = strRows[r].Split(‘:‘)[1].Trim().Replace(",", ",").Replace(":", ":").Replace("\"", "");
}
tb.Rows.Add(dr);
tb.AcceptChanges();
}
return tb;
}
#endregion
#region 根据DataTable生成EasyUI Tree Json树结构
/// <summary>
/// 根据DataTable生成EasyUI Tree Json树结构
/// </summary>
/// <param name="tabel">数据源</param>
/// <param name="idCol">ID列</param>
/// <param name="txtCol">Text列</param>
/// <param name="url">节点Url</param>
/// <param name="rela">关系字段</param>
/// <param name="pId">父ID</param>
/// <example>string json = GetTreeJsonByTable(dt, "id", "name", "url", "fatherid", "0");</example>
private string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string url, string rela, object pId)
{
StringBuilder result = new StringBuilder();
StringBuilder sb = new StringBuilder();
result.Append(sb.ToString());
sb.Length = 0;
if (tabel.Rows.Count > 0)
{
sb.Append("[");
string filer = string.Format("{0}=‘{1}‘", rela, pId);
DataRow[] rows = tabel.Select(filer);
if (rows.Length > 0)
{
foreach (DataRow row in rows)
{
sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"attributes\":\"" + row[url] + "\",\"state\":\"open\"");
if (tabel.Select(string.Format("{0}=‘{1}‘", rela, row[idCol])).Length > 0)
{
sb.Append(",\"children\":");
GetTreeJsonByTable(tabel, idCol, txtCol, url, rela, row[idCol]);
result.Append(sb.ToString());
sb.Length = 0;
}
result.Append(sb.ToString());
sb.Length = 0;
sb.Append("},");
}
sb = sb.Remove(sb.Length - 1, 1);
}
sb.Append("]");
result.Append(sb.ToString());
sb.Length = 0;
}
return result.ToString();
}
#endregion
}