ASP.NET 将DataTable解析成JSON简介
这里解析json使用的是Newtonsoft.Json.dll程序集。下面请看code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Newtonsoft.Json;
/// <summary>
///DataTable解析JSON
/// </summary>
public class ConvertDataTable : JsonConverter
{
public ConvertDataTable()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public override bool CanConvert(Type objectType)
{
return typeof(DataTable).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value)
{
DataTable dt = (DataTable)value;
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();
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Newtonsoft.Json;
/// <summary>
///DataTable解析JSON
/// </summary>
public class ConvertDataTable : JsonConverter
{
public ConvertDataTable()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public override bool CanConvert(Type objectType)
{
return typeof(DataTable).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value)
{
DataTable dt = (DataTable)value;
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();
}
}
使用上面这个类,然后再调用下面这个方法,就可以将datatable转换成json了。
JavaScriptConvert.SerializeObject(dt, new ConvertDataTable())