首页 > 代码库 > ASP.NET 将DataTable解析成JSON简介
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())
ASP.NET 将DataTable解析成JSON简介
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。