并非原创,在网上找到的,没找到出处
调用的时候直接string json = JavaScriptConvert.SerializeObject(ds, new DataSetConverter());
下面是DataSetConverter这个类的实现
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(); } public override object ReadJson(JsonReader reader, Type objectType) { throw new NotImplementedException(); } }