asp.net DataTable和Dataset序列化成Json格式
DataTableToJson:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization.Json; using System.Runtime.Serialization; using System.IO; using System.Web.Script.Serialization; using MicroBlog.Common.APIHelper; using System.Web; namespace MicroBlog.Common.APIHelper { public class Resolve { /// <summary> /// JSON文本转对象,泛型方法 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="jsonText">JSON文本</param> /// <returns>指定类型的对象</returns> public static T JSONToObject<T>(string jsonText, HttpContext context) { JavaScriptSerializer jss = new JavaScriptSerializer(); try { return jss.Deserialize<T>(jsonText); } catch (Exception ex) { return default(T); } } /// <summary> /// 将JSON文本转换成数据行 /// </summary> /// <param name="jsonText">JSON文本</param> /// <returns>数据行的字典</returns> public static Dictionary<string, object> DataRowFromJSON(string jsonText, HttpContext context) { return JSONToObject<Dictionary<string, object>>(jsonText, context); } } }调用的话:Dictionary<string, object> dt = Resolve.DataRowFromJSON(requestbuffer, context);
DatasetToJson:
public class DataSetConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(DataSet).IsAssignableFrom(objectType); } public override void WriteJson(JsonWriter writer, object value) { DataSet ds = (DataSet)value; writer.WriteStartObject(); foreach (DataTable dt in ds.Tables) { writer.WritePropertyName(dt.TableName); writer.WriteStartArray(); foreach (DataRow dr in dt.Rows) { writer.WriteStartObject(); foreach (DataColumn dc in dt.Columns) { writer.WritePropertyName(dc.ColumnName); writer.WriteValue(dr[dc].ToString()); } writer.WriteEndObject(); } writer.WriteEndArray(); } writer.WriteEndObject(); } }调用的话:JavaScriptConvert.SerializeObject(GetTestDataTable(), new DataTableConverter());