DataTable、Model轉json

來源:互聯網
上載者:User

標籤:ram   item   cat   datetime   ace   json格式   tty   agg   ==   

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;
}

DataTable、Model轉json

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.