DataTable、Model转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;
}

时间: 2024-10-17 02:52:03

DataTable、Model转json的相关文章

C#将datatable数据转换成JSON数据的方法

json数据类型格式:[{id:"1",code:"1",description:"博士"},{id:"2",code:"2",description:"硕士"},{id:"3",code:"3",description:"学士"}] //参考代码public string DataTableToJson(string json

Datatable/Dataset 转 JSON方法

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Text; /// <summary> ///DataHelper 的摘要说明 /// </summary> public class DataHelper { public DataHelper() { // //TODO: 在此处添加构造函数逻辑

DataTable 对象 转换为Json 字符串

#region DataTable 转换为Json 字符串 /// <summary> /// DataTable 对象 转换为Json 字符串 /// </summary> /// <param name="dt"></param> /// <returns></returns> public string ToJson( DataTable dt) { JavaScriptSerializer javaScri

ASP.NET 将DataTable解析成JSON简介

这里解析json使用的是Newtonsoft.Json.dll程序集.下面请看code: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using Newtonsoft.Json; /// <summary> ///DataTable解析JSON /// </summary> public class ConvertDat

.NET中把DataTable转换成JSON的总结

最近在做公司的一个project,其中有一部分,要求浏览器端通过jquery ajax调用服务器端返回json格式的多条数据.网上搜索了一下,找到下面两个方法在.NET中生成json. 方法一:.NET Framework 3.0及更早的版本: public static string GetJSONString(DataTable Dt) { string[] StrDc = new string[Dt.Columns.Count]; string HeadStr = string.Empty

DataTable 转换成 Json的3种方法

在web开发中,我们可能会有这样的需求,为了便于前台的JS的处理,我们需要将查询出的数据源格式比如:List<T>.DataTable转换为Json格式.特别在使用Extjs框架的时候,Ajax异步请求的数据格式就是Json.鉴于此,我今天来分享将DataTable 转换成 Json的3种方法.换句话说如何在ASP.NET将一个DataTable序列化为 Json数组.或者如何从一个DataTable返回一个Json字符串.这篇文章将采用StringBuilder,JavaScriptSeri

C# DataTable 转换成JSON数据

原文:C# DataTable 转换成JSON数据 using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; using System.Web.Script.Serialization; namespace WsDemo { public class DataTableConvertJson { #region

.NET DataTable DataSet转json代码

/// <summary> /// dataTable转换成Json格式 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string ToJson(DataTable dt) { StringBuilder jsonBuilder = new StringBuilder(); jsonBuilde

DataTable转化为Json数组

在项目中,如果用到Ajax就经常要用到将后台得到的数据比如DataTable转换为Json字符串.在这里向大家分享一个DataTable转Json的方法: 1 public static string DtToSON(DataTable dt) 2 { 3 StringBuilder jsonBuilder = new StringBuilder(); 4 jsonBuilder.Append("["); 5 for (int i = 0; i < dt.Rows.Count;