DataTableModel转json
Posted D调灬仔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DataTableModel转json相关的知识,希望对你有一定的参考价值。
public static string DateFormatString { get; set; }
public static string DefaultJson = "{}";
/// <summary>
/// 转义html
/// </summary>
/// <param name="htmlStr"></param>
public static string ConvertHtml(string htmlStr)
{
if ((htmlStr + "").Length > 0)
{
return htmlStr.Replace("\\\"", "\"")
.Replace("\"", "\\\"")
.Replace("\\", "\\\\")
.Replace("\r", "<br/>")
.Replace("\n", "<br/>")
.Replace("\t", "")
.Trim();
}
return "";
}
public static string TrimStr(object str)
{
if (str == null) return "";
switch (str.GetType().Name)
{
case "Int32":
return str.ToString();
break;
case "DateTime":
if (string.IsNullOrEmpty(DateFormatString))
DateFormatString = "yyyy-MM-dd HH:mm:ss";
return (str is DateTime ? (DateTime)str : new DateTime()).ToString(DateFormatString);
break;
case "String":
return (str + "").Length > 0 ? str.ToString() : "";
break;
default:
return str.ToString();
break;
}
}
/// <summary>
/// 封装json字符串
/// </summary>
/// <param name="fields">字段数组</param>
/// <param name="values">值数组</param>
/// <returns></returns>
public static string ArrayToJson(string[] fields, string[] values, bool isConvent = true)
{
var jsonStringBuilder = new StringBuilder("{");
int i = 0;
if (fields.Length > 0 && fields.Length <= values.Length)
{
if (isConvent)
{
foreach (string value in values)
{
jsonStringBuilder.Append("\"" + fields[i++] + "\":\"" + ConvertHtml(TrimStr(value.Trim())) +
"\",");
}
}
else
{
foreach (string value in values)
{
jsonStringBuilder.Append("\"" + fields[i++] + "\":" + TrimStr(value.Trim()) +
",");
}
}
jsonStringBuilder = jsonStringBuilder.Remove(jsonStringBuilder.Length - 1, 1);
}
jsonStringBuilder.Append("}");
return jsonStringBuilder.ToString();
}
/// <summary> DataTable二维表格转为符合json格式的字符串 </summary>
/// <param name="tableSource">数据库查询结果</param>
/// <param name="gnorgColumn">过滤列</param>
/// <param name="isChilid">是否是子节点</param>
/// <returns></returns>
public static string DataTableToJsonByIgnorg(DataTable tableSource, string[] gnorgColumn = null,
bool isChilid = false)
{
var columnStrings = new List<string>();
foreach (DataColumn column in tableSource.Columns)
{
if (gnorgColumn != null && gnorgColumn.Contains(column.ColumnName))
{
continue;
}
columnStrings.Add(column.ColumnName);
}
return DataTableToJson(tableSource, columnStrings.ToArray(), isChilid);
}
/// <summary> DataTable二维表格转为符合json格式的字符串 </summary>
/// <param name="tableSource">数据库查询结果</param>
/// <param name="fields">需要添加进来的字段名</param>
/// <param name="isChild">是否是子节点</param>
/// <returns></returns>
public static string DataTableToJson(DataTable tableSource, string[] fields, bool isChild = false)
{
var jsonData = new StringBuilder("{\"totalCount\":" + tableSource.Rows.Count + ",\"items\":[");
if (isChild)
jsonData = new StringBuilder("[");
if (tableSource.Rows.Count > 0)
{
foreach (DataRow row in tableSource.Rows)
{
jsonData.Append("{");
jsonData = fields.Aggregate(jsonData,
(current, t) => current.Append(("\"" + t + "\":\"" + ConvertHtml(TrimStr(row[t])) + "\",")));
jsonData = jsonData.Remove(jsonData.Length - 1, 1);
jsonData.Append("},");
}
jsonData = jsonData.Remove(jsonData.Length - 1, 1);
}
jsonData.Append(isChild ? "]" : "]}");
return jsonData.ToString();
}
public static string ConvertToJson<T>(T t) where T : class
{
if (t == null) return "{}";
var jsonData = new StringBuilder();
jsonData.Append("{");
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
jsonData.Append(("\"" + pi.Name + "\":\"" +
ConvertHtml(TrimStr(pi.GetValue(t, null))) + "\","));
}
jsonData = jsonData.Remove(jsonData.Length - 1, 1);
jsonData.Append("}");
return jsonData.ToString();
}
/// <summary>
/// model列表转化为json
/// </summary>
/// <param name="ts">model列表</param>
/// <param name="isChild">是否是子节点</param>
/// <returns></returns>
public static string ConvertToJson<T>(IList<T> ts, bool isChild = false) where T : class
{
if (ts == null) return DefaultJson;
var jsonData = new StringBuilder("{\"totalCount\":" + ts.Count + ",\"items\":[");
if (isChild)
jsonData = new StringBuilder("[");
foreach (T t in ts)
{
jsonData.Append("{");
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
jsonData.Append(("\"" + pi.Name + "\":\"" +
ConvertHtml(TrimStr(pi.GetValue(t, null))) +
"\","));
}
jsonData = jsonData.Remove(jsonData.Length - 1, 1);
jsonData.Append("},");
}
if (ts.Count > 0)
jsonData = jsonData.Remove(jsonData.Length - 1, 1);
jsonData.Append(isChild ? "]" : "]}");
return jsonData.ToString();
}
/// <summary>
/// model列表转化为json
/// </summary>
/// <param name="ts">model列表</param>
/// <param name="isHasChild">是否有子节点</param>
/// <returns></returns>
public static string ConvertToJson<T>(IList<T> ts, int isHasChild) where T : class
{
if (ts == null) return DefaultJson;
var jsonData = new StringBuilder("{\"totalCount\":" + ts.Count + ",\"items\":");
jsonData.Append(isHasChild == 1 ? GetJson(ts) : "[]");
jsonData.Append("}");
return jsonData.ToString();
}
/// <summary>
/// model列表转化为json
/// </summary>
/// <param name="ts">model列表</param>
/// <param name="isHasChild">是否有子节点</param>
/// <returns></returns>
public static string ConvertToJson<T>(T ts, int isHasChild) where T : class
{
if (ts == null) return DefaultJson;
var jsonData = new StringBuilder("{\"totalCount\":1,\"items\":");
jsonData.Append(isHasChild == 1 ? GetJson(ts) : "[]");
jsonData.Append("}");
return jsonData.ToString();
}
public static string GetJson(object obj)
{
string str;
try
{
var js = new javascriptSerializer { MaxJsonLength = int.MaxValue };
str = js.Serialize(obj);
}
catch
{
str = "";
}
return str;
}
以上是关于DataTableModel转json的主要内容,如果未能解决你的问题,请参考以下文章
剑指offer知识点List转int[],List转String,String转int,char[]转String,String 转char[],List转String[]
剑指offer知识点List转int[],List转String,String转int,char[]转String,String 转char[],List转String[]
剑指offer知识点List转int[],List转String,String转int,char[]转String,String 转char[],List转String[]
经纬度之间互相转换(高德转百度,高德转wgs84,百度转高德,百度转wgs84,wgs84转百度,wgs84转高德)