using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.IO;
using System.Text;
///
///JsonHelper 的摘要说明
/// public class JsonHelper
{
public JsonHelper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
///
/// 对象转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 List
> DataTableToList(DataTable dt)
{
List> list= new List>();
foreach (DataRow dr in dt.Rows)
{
Dictionary dic = new Dictionary();
foreach (DataColumn dc in dt.Columns)
{
dic.Add(dc.ColumnName, dr[dc.ColumnName]);
}
list.Add(dic);
}
return list;
}
///
/// 数据集转键值对数组字典
///
/// 数据集
/// 键值对数组字典
public static Dictionary>> DataSetToDic(DataSet ds)
{
Dictionary>> result = new Dictionary>>();
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 Dictionary>> TablesDataFromJSON(string jsonText)
{
return JSONToObject>>>(jsonText);
}
///
/// 将JSON文本转换成数据行
///
/// JSON文本
/// 数据行的字典
public static Dictionary DataRowFromJSON(string jsonText)
{
return JSONToObject>(jsonText);
}
//JSON序列化的辅助类
public static string Serialize(T data)
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, data);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
//反序列化的辅助类
public static T Deserialize(string json)
{
T obj = Activator.CreateInstance();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
}
阅读(258) | 评论(0) | 转发(0) |