JsonHelper
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Newtonsoft.Json;
using System.Text;
using System.IO;
using System.Reflection;
/// <summary>
///JsonHelper 的摘要说明
/// </summary>
public class JsonHelper
{
public JsonHelper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 将表的数据序列化为JSON串
/// </summary>
/// <param name="dt"></param>
/// <param name="dtName"></param>
/// <returns></returns>
public static string DataTableToJSON(DataTable 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.Rows)
{
jw.WriteStartObject();
foreach (DataColumn dc in dt.Columns)
{
jw.WritePropertyName(dc.ColumnName);
ser.Serialize(jw, dr[dc].ToString());
}
jw.WriteEndObject();
}
jw.WriteEndArray();
jw.WriteEndObject();
sw.Close();
jw.Close();
}
return sb.ToString();
}
/// <summary>
/// 将对象序列化为JSON串
/// </summary>
/// <typeparam name="T">对象的数据类型</typeparam>
/// <param name="obj">对象</param>
/// <returns>JSON串</returns>
public static string ObjectToJSON<T>(T obj)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jw = new JsonTextWriter(sw))
{
JsonSerializer ser = new JsonSerializer();
jw.WriteStartObject();
T o = Activator.CreateInstance<T>();
PropertyInfo[] pi = o.GetType().GetProperties();
foreach (PropertyInfo p in pi)
{
jw.WritePropertyName(p.Name);
var values = p.GetValue(obj, null);
ser.Serialize(jw, p.GetValue(obj, null));
}
jw.WriteEndObject();
sw.Close();
jw.Close();
}
string a = sb.ToString();
return sb.ToString();
}
/// <summary>
/// 将集合序列化为JSON串
/// </summary>
/// <typeparam name="T">集合中的对象的数据类型</typeparam>
/// <param name="obj">对象</param>
/// <returns>JSON串</returns>
/// <summary>
/// 将集合序列化为JSON串
/// </summary>
/// <typeparam name="T">集合中的对象的数据类型</typeparam>
/// <param name="list">泛型集合</param>
/// <param name="jsonName">集合对象的名称</param>
/// <returns>JSON串</returns>
public static string ListToJSON<T>(IList<T> list, string jsonName)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jw = new JsonTextWriter(sw))
{
JsonSerializer ser = new JsonSerializer();
jw.WriteStartObject();
jw.WritePropertyName(jsonName);
jw.WriteStartArray();
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
jw.WriteStartObject();
T obj = Activator.CreateInstance<T>();
PropertyInfo[] pi = obj.GetType().GetProperties();
foreach (PropertyInfo p in pi)
{
jw.WritePropertyName(p.Name);
ser.Serialize(jw, p.GetValue(list[i], null));
}
jw.WriteEndObject();
}
}
jw.WriteEndArray();
jw.WriteEndObject();
sw.Close();
jw.Close();
}
return sb.ToString();
}
}