C# json帮助类,JsonHelper
2021-03-28 05:25
标签:sum 数组 new tostring ase 格式 for ict json /// foreach (DataColumn dc in dt.Tables[0].Columns) jw.WriteEndObject(); sw.Close(); /// throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message); /// foreach (DataRow dr in dt.Rows) /// foreach (DataTable dt in ds.Tables) return result; /// /// /// /// C# json帮助类,JsonHelper 标签:sum 数组 new tostring ase 格式 for ict json 原文地址:https://www.cnblogs.com/-hao/p/9342854.html
/// json帮助类
///
public class JsonHelper
{
public JsonHelper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public static string DataTableToJSON(DataSet dt, string dtName)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jw = new JsonTextWriter(sw))
{
JsonSerializer ser = new JsonSerializer();
jw.WriteStartObject();
jw.WritePropertyName(dtName);
jw.WriteStartArray();
foreach (DataRow dr in dt.Tables[0].Rows)
{
jw.WriteStartObject();
{
jw.WritePropertyName(dc.ColumnName);
ser.Serialize(jw, dr[dc].ToString());
}
}
jw.WriteEndArray();
jw.WriteEndObject();
jw.Close();
}
return sb.ToString();
}
/// 对象转JSON
///
/// 对象
///
public static string ObjectToJSON(object obj)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
return jss.Serialize(obj);
}
catch (Exception ex)
{
}
}
/// 数据表转键值对集合 www.2cto.com
/// 把DataTable转成 List集合, 存每一行
/// 集合中放的是键值对字典,存每一列
///
/// 数据表
///
public static List
{
List
{
Dictionary
foreach (DataColumn dc in dt.Columns)
{
dic.Add(dc.ColumnName, dr[dc.ColumnName]);
}
list.Add(dic);
}
return list;
}
/// 数据集转键值对数组字典
///
/// 数据集
///
public static Dictionary
{
Dictionary
result.Add(dt.TableName, DataTableToList(dt));
}
/// 数据表转JSON
///
/// 数据表
///
public static string DataTableToJSON(DataTable dt)
{
return ObjectToJSON(DataTableToList(dt));
}
/// JSON文本转对象,泛型方法
///
///
/// JSON文本
///
public static T JSONToObject
{
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
return jss.Deserialize
}
catch (Exception ex)
{
throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
}
}
/// 将JSON文本转换为数据表数据
///
/// JSON文本
///
public static Dictionary
{
return JSONToObject
}
/// 将JSON文本转换成数据行
///
/// JSON文本
///
public static Dictionary
{
return JSONToObject
}
}