C# Datatable、DataReader等转化json
//对象转换为Json字符串
public static string ToJson(object jsonObject)
{
object objectValue = string.Empty;
string jsonString = "{";
if (jsonObject==null)
{
return jsonString + "}";
}
PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
for (int i = 0; i < propertyInfo.Length; i++)
{
try
{
objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, BindingFlags.InvokeMethod, null, new object[] { }, null);
string value = string.Empty;
if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
{
value = "'" + objectValue.ToString() + "'";
}
else if (objectValue is string)
{
value = "'" + ToJson(objectValue.ToString()) + "'";
}
else if (objectValue is IEnumerable)
{
value = ToJson((IEnumerable)objectValue);
}
else
{
value = ToJson(objectValue.ToString());
}
jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
}
catch (Exception ex)
{
string s = ex.Message;
}
}
jsonString.Remove(jsonString.Length - 1);
return jsonString + "}";
} //对象集合转换Json
public static string ToJson(IEnumerable array)
{
if (array == null) return "";
string jsonString = "[";
foreach (object item in array)
{
jsonString+= ToJson(item) + ",";
}
jsonString.Remove(jsonString.Length - 1);
return jsonString + "]";
}
//普通集合转换Json
public static string ToArrayString(IEnumerable array)
{
if (array == null) return "";
string jsonString = "[";
foreach (object item in array)
{
jsonString = ToJson(item.ToString()) + ",";
}
jsonString.Remove(jsonString.Length - 1, jsonString.Length);
return jsonString + "]";
}
//Datatable转换为Json
public static string ToJson(DataTable dt)
{
if (dt == null || dt.Rows.Count == 0) return "[{}]";
StringBuilder jsonString = new StringBuilder(); jsonString.Append("[");
DataRowCollection drc = dt.Rows;
for (int i = 0; i < drc.Count; i++)
{
jsonString.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
string strKey = dt.Columns[j].ColumnName;
string strValue = drc[i][j].ToString();
Type type = dt.Columns[j].DataType;
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if(j<dt.Columns.Count-1)
jsonString.Append(strValue + ",");
else
jsonString.Append(strValue);
}
jsonString.Append("},");
}
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
}
//DataTable转成Json
public static string ToJson(DataTable dt, string jsonName)
{
if(string.IsNullOrEmpty(jsonName))
jsonName = dt.TableName;
StringBuilder sb = new StringBuilder();
sb.Append("{\"" + jsonName + "\":[");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
sb.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
Type type = dt.Rows[i][j].GetType();
sb.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
if (j < dt.Columns.Count - 1)
{
sb.Append(",");
}
}
sb.Append("}");
if (i < dt.Rows.Count - 1)
{
sb.Append(",");
}
}
}
sb.Append("]}");
return sb.ToString();
} //DataReader转换为Json
public static string ToJson(DbDataReader dataReader)
{
StringBuilder jsonString = new StringBuilder();
jsonString.Append("[");
while (dataReader.Read())
{
jsonString.Append("{");
for (int i = 0; i < dataReader.FieldCount; i++)
{
Type type = dataReader.GetFieldType(i);
string strKey = dataReader.GetName(i);
string strValue = dataReader[i].ToString();
jsonString.Append("\"" + strKey + "\":");
strValue = StringFormat(strValue, type);
if (i < dataReader.FieldCount - 1)
{
jsonString.Append(strValue + ",");
}
else
{
jsonString.Append(strValue);
}
}
jsonString.Append("},");
}
dataReader.Close();
jsonString.Remove(jsonString.Length - 1, 1);
jsonString.Append("]");
return jsonString.ToString();
} //DataSet转换为Json
public static string ToJson(DataSet dataSet)
{
string jsonString = "{";
foreach (DataTable table in dataSet.Tables)
{
jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
}
jsonString = jsonString.TrimEnd(',');
return jsonString + "}";
}
//ArrayList转化为json
public static string ArryListToJson(ArrayList alist, string jsonName)
{
string json = string.Empty;
string strSubList = "\"" + jsonName + "\":" + "[{";
for (int i = 0; i < alist.Count; i++)
{
Hashtable ht1 = (Hashtable)alist[i];
foreach (DictionaryEntry de in ht1)
{
if (de.Value is ArrayList)
{
strSubList += ArryListToJson((ArrayList)de.Value, de.Key.ToString());
strSubList += "]";
}
else
{
strSubList += "\"" + de.Key + "\":" + "\"" + de.Value + "\",";
}
}
strSubList = strSubList.Remove(strSubList.Length - 1);
strSubList += "},{";
}
if (strSubList.Length >= 2)
{
json = strSubList.Remove(strSubList.Length - 2);
}
json += "]";
return json;
}
//Hashtable To Json
public static string HashtableToJson(Hashtable hr)
{
string json = "{";
foreach (DictionaryEntry row in hr)
{
try
{
string key = "\"" + row.Key + "\":";
string value = string.Empty; if (row.Value is ArrayList)
{
key = string.Empty;
value = ArryListToJson((ArrayList)row.Value, row.Key.ToString());
value += ",";
}
else
{
value = "\"" + (row.Value == null ? "" : row.Value.ToString()) + "\",";
}
json += key + value;
}
catch (Exception ex)
{
string mess = ex.Message;
}
}
json = json.Remove(json.Length - 1);
json = json + "}";
return json;
}
//转换字符格式
private static string StringFormat(string str, Type type)
{
if (string.IsNullOrEmpty(str)) return "\"\"";
if (type == typeof(string))
{
str = "\"" + ConvertStrToSpecificationStrs(str) + "\"";
}
else if (type == typeof(DateTime))
{
str = "\"" + str + "\"";
}
else if (type == typeof(bool))
{
str = str.ToLower();
}
return str;
}
//转换字符格式
public static string ConvertStrToSpecificationStrs(string str)
{
if (string.IsNullOrEmpty(str)) return "";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
char cStr = str.ToCharArray()[i]; switch (cStr)
{
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(cStr); break;
}
}
return sb.ToString();
}
C# Datatable、DataReader等转化json的更多相关文章
- [Json] C#ConvertJson|List转成Json|对象|集合|DataSet|DataTable|DataReader转成Json (转载)
点击下载 ConvertJson.rar 本类实现了 C#ConvertJson|List转成Json|对象|集合|DataSet|DataTable|DataReader转成Json|等功能大家先预 ...
- Asp.net常用开发方法之DataTable/DataReader转Json格式代码
public static string JsonParse(OleDbDataReader dataReader) //DataRead转json { StringBuilder jsonStrin ...
- C#中DataTable转化JSON
[WebMethod(Description = "将一个DataTable对象转化成JSON")] public string GetJSON() { JavaScriptSer ...
- 泛型集合、datatable常用数据类型转换Json帮助类
泛型集合.datatable常用数据类型转换Json帮助类 using System; using System.Data; using System.Configuration; using Sys ...
- Asp.net 将DataTable 或者DataSet 转换为Json 格式
Web 开发中,将从数据库中取到的数据直接转换为 Json 格式的数据,在前台通过Ajax 无刷新显示在界面上,下面提供将DataTable 或者DataSet 转换为Json 的方法 /// < ...
- DataTable ,XML和JSON相互转化
网上搜集的,保留下来了,有需要的拿去!private string DataTable2Xml(DataTable dt) { StringBuilder xmlBuilder = new Strin ...
- Js:消息弹出框、获取时间区间、时间格式、easyui datebox 自定义校验、表单数据转化json、控制两个日期不能只填一个
(function ($) { $.messageBox = function (message) { $.messager.show({ title:'消息框提示', msg:message, sh ...
- form表单转化json对象
利用 $.fn 可以让每一个jquery 对象都能直接使用这个方法. //form表单转化json对象$.fn.serializeObject = function () { var o = {}; ...
- DataTable序列化及反序列化Json
添加Json解析引用 using Newtonsoft.Json; 实现方式一:普通转换 private void button1_Click(object sender, EventArgs e) ...
随机推荐
- jQuery获取各种标签的文本和value值
<select id="test"> <option value ="volvo">Volvo</option> <o ...
- 【AtCoder】 ARC 096
link C-Half and Half 题意:三种pizza,可以花\(A\)价钱买一个A-pizza,花\(B\)价钱买一个B-pizza,花\(C*2\)价钱买A-pizza和B-pizza各一 ...
- 转载:关于思科交换机、路由器如何关闭telnet 开启ssh服务
等保测评要求: 必须关闭telnet服务,开启ssh服务 即用ssh方式登录网络设备,而不允许用telnet. 输入密码.en 再次输入密码.sh run 这些常规动作就不再赘述. 1.关闭telne ...
- IntelliJ IDEA 快捷键终极大全,速度收藏!
阅读本文大概需要 6 分钟. ▌自动代码 常用的有 fori/sout/psvm+Tab 即可生成循环.System.out.main 方法等 boilerplate 样板代码 . 例如要输入 fo ...
- [Beta阶段]第二次Scrum Meeting
Scrum Meeting博客目录 [Beta阶段]第二次Scrum Meeting 基本信息 名称 时间 地点 时长 第二次Scrum Meeting 19/05/03 大运村寝室6楼 40min ...
- IIS部署Silverlight
题设: 网站如果应用了Silverlight技术,直接部署到IIS中是无法正常运行的, 分析: 因为Silverlight应用所对应的三种MIME类型没有在IIS中注册,所以Silverlight相关 ...
- 【转】linux sed命令
转自:linux sed命令就是这么简单 参考:Linux三大剑客之sed:https://blog.csdn.net/solaraceboy/article/details/79272344 阅读目 ...
- VUE 动态加载组件的四种方式
动态加载组件的四种方式: 1.使用import导入组件,可以获取到组件 var name = 'system'; var myComponent =() => import('../compon ...
- Oracle 03113
SYSTEM的只有2M可以用了,还是需要 扩增 SYSTEM和SYSAUX的表空间 SELECT a.tablespace_name,a.bytes/1024/1024 total_M,b.bytes ...
- Keras split train test set when using ImageDataGenerator
Keras split train test set when using ImageDataGenerator I have a single directory which contains su ...