ASP.NET(C#) Json序列化反序列化帮助类Jsonhelper
标签:rom code http har targe public 键值 sum too
原文地址:https://ken.io/note/csharp-asp.net-jsonhelper
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Script.Serialization;
using System.Data;
namespace Utils
{
///
/// JSON帮助类
///
public class JsonHelper
{
///
/// 对象转JSON
///
/// 对象
/// JSON格式的字符串
public static string ObjectToJSON(object obj)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
return jss.Serialize(obj);
}
catch (Exception ex)
{
throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
}
}
///
/// 数据表转键值对集合
/// 把DataTable转成 List集合, 存每一行
/// 集合中放的是键值对字典,存每一列
///
/// 数据表
/// 哈希表数组
public static Liststring, object>> DataTableToList(DataTable dt)
{
Liststring, object>> list
= new Liststring, object>>();
foreach (DataRow dr in dt.Rows)
{
Dictionarystring, object> dic = new Dictionarystring, object>();
foreach (DataColumn dc in dt.Columns)
{
dic.Add(dc.ColumnName, dr[dc.ColumnName]);
}
list.Add(dic);
}
return list;
}
///
/// 数据集转键值对数组字典
///
/// 数据集
/// 键值对数组字典
public static Dictionarystring, Liststring, object>>> DataSetToDic(DataSet ds)
{
Dictionarystring, Liststring, object>>> result = new Dictionarystring, Liststring, object>>>();
foreach (DataTable dt in ds.Tables)
result.Add(dt.TableName, DataTableToList(dt));
return result;
}
///
/// 数据表转JSON
///
/// 数据表
/// JSON字符串
public static string DataTableToJSON(DataTable dt)
{
return ObjectToJSON(DataTableToList(dt));
}
///
/// JSON文本转对象,泛型方法
///
/// 类型
/// JSON文本
/// 指定类型的对象
public static T JSONToObject(string jsonText)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
return jss.Deserialize(jsonText);
}
catch (Exception ex)
{
throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
}
}
///
/// 将JSON文本转换为数据表数据
///
/// JSON文本
/// 数据表字典
public static Dictionarystring, Liststring, object>>> TablesDataFromJSON(string jsonText)
{
return JSONToObjectstring, Liststring, object>>>>(jsonText);
}
///
/// 将JSON文本转换成数据行
///
/// JSON文本
/// 数据行的字典
public static Dictionarystring, object> DataRowFromJSON(string jsonText)
{
return JSONToObjectstring, object>>(jsonText);
}
}
}
ASP.NET(C#) Json序列化反序列化帮助类Jsonhelper
标签:rom code http har targe public 键值 sum too
原文地址:https://www.cnblogs.com/zhaoyl9/p/11307190.html
评论