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();
}
}

使用上面这个类,然后再调用下面这个方法,就可以将datatable转换成json了。

JavaScriptConvert.SerializeObject(dt, new ConvertDataTable())
posted @ 2014-11-21 17:00  w__s  阅读(230)  评论(0编辑  收藏  举报