ASP.NET:JSONHelper:json扩展类
2013-02-22 15:46
459 查看
说明:这个是我在写的工具类库中的一个扩展类,主要实现了DataTable(DataSet),List,Object转换成json对象的功能,今天修复了一个小bug,目前版本号为1.0.1等过段时间工具类库中的linq写完了我会再看看是否还有扩展的需要,到时再放出整个类库
========================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
namespace VincentLinq
{
///
/// 版本:1.0.1
///
用于将object,list,string,datatable等转换为json对象的类
/// 作者:Vincent 2012年9月8日
19:49:27
///
public class
JSONHelper
{
///
/// 将DataTable对象转换为json对象
///
/// DataTable对象
/// json格式的字符串
public static string
ConvertDataTableToJSON(DataTable dt)
{
System.Text.StringBuilder sb = new
System.Text.StringBuilder("[");
foreach
(DataRow row in dt.Rows)
{
sb.Append("{");
foreach (DataColumn col in
dt.Columns)
{
if (row.IsNull(col.ColumnName) == false)
{
if
(col.DataType != typeof(int) && col.DataType !=
typeof(float) && col.DataType != typeof(decimal) &&
col.DataType != typeof(double))
{
string str =
row[col.ColumnName].ToString();
str = str.Replace("[",
"【")
.Replace("]", "】")
.Replace(".", "。")
.Replace("{", "{")
.Replace("}", "}")
.Replace("\", "\\\")
.Replace(",", ",")
.Replace("\'", "‘")
.Replace(""", "”")
.Replace("\n", "")
.Replace("\r","")
.Replace("\n\r","")
.Replace(":", ":")
.Replace("-", "_")
.Replace("(", "(")
.Replace(")", ")")
.Replace("
","")
.Replace("
","")
.Replace("\t","");
sb.Append(""" +
col.ColumnName + "":"" + str + """);
}
else
{
string str =
row[col.ColumnName].ToString();
sb.Append(""" +
col.ColumnName + "":" + str);
}
}
else
sb.Append(""" + col.ColumnName + "":" + "");
sb.Append(",");
}
sb.Remove(sb.ToString().LastIndexOf(","),
1);//移除最后一个逗号,保证[{"col1":"lie","col2":"lie2"
sb.Append("},");//保证此时为[{"col1":"lie","col2":"lie2"},
}
//
sb.Remove(sb.ToString().LastIndexOf(","),
1);//保证此时为[{"col1":"lie","col2":"lie2"},{"col4":"lie","col5":"lie2"}
int start1
= sb.ToString().LastIndexOf(",");
if (start1
!= -1)
sb.Remove(start1,
1);//去除最后一个,
sb.Append("]");
return
sb.ToString();
}
///
/// 将集合转换为JSON
///
/// 类型
/// 集合对象
/// JSON对象
public static string
ConvertListToJSON(IEnumerable list) where T : new()
{
int
start1;
System.Text.StringBuilder sb = new
System.Text.StringBuilder("[");
foreach (T
t in list)
{
sb.Append("{");
Type type =
t.GetType();
PropertyInfo[] props =
type.GetProperties();
foreach (PropertyInfo p in
props)
{
object[] obj =
p.GetCustomAttributes(typeof(VincentLinqColumnAttribute),
false);
if (obj.Count() > 0)
{
VincentLinqColumnAttribute field = obj[0] as
VincentLinqColumnAttribute;
if (field
!= null)
{
string attrName =
field.ColumnName;
object attrValue =
p.GetValue(t, null);
if (attrValue == null)
{
sb.Append(""" + attrName + "":"" + null +
"",");
}
else if (attrValue is string
|| attrValue is DateTime)
{
string value = attrValue.ToString();
value = value.Replace(""", "“")
.Replace("\", "\\\")
.Replace(":", ":")
.Replace("\'", "’")
.Replace("\n", "")
.Replace("\r", "")
.Replace("\n\r", "");
sb.Append(""" + attrName + "":"" + value +
"",");
}
else
{
sb.Append(""" + attrName + "":" +
attrValue.ToString()+",");
}
}
}
//sb.Append(",");这地方append逗号会生成错误json,当有属性没有添加特性的时候会有bug
}
start1 =
sb.ToString().LastIndexOf(",");
if (start1 != -1)
{
sb.Remove(start1, 1);
}
sb.Append("},");
}
start1 =
sb.ToString().LastIndexOf(",");
if (start1
!= -1)
{
sb.Remove(start1, 1);
}
sb.Append("]");
return
sb.ToString();
}
///
/// 根据传入的对象获得该对象对应的JSON
///
/// 实体对象
/// JSON
public static string ConvertObjectToJSON(object
target)
{
Type type
= target.GetType();
PropertyInfo[] props = type.GetProperties();
System.Text.StringBuilder sb = new
System.Text.StringBuilder("[{");
foreach
(PropertyInfo p in props)
{
object[] objs =
p.GetCustomAttributes(typeof(VincentLinqColumnAttribute),
false);
if (objs.Count() >
0)
{
VincentLinqColumnAttribute field = objs[0] as
VincentLinqColumnAttribute;
string attrName = field.ColumnName;
object attrValue = p.GetValue(target,
null);
if (attrValue == null)
{
sb.Append(""" + attrName + "":"" + null + "",");
}
else if (attrValue is string || attrValue is
DateTime)
{
string
value = attrValue.ToString();
value =
value.Replace(""", "“")
.Replace("\", "\\\")
.Replace(":", ":")
.Replace("\'", "’")
.Replace("\n", "")
.Replace("\r", "")
.Replace("\n\r", "");
sb.Append(""" + attrName + "":"" + value + "",");
}
else
{
sb.Append(""" + attrName + "":" +
attrValue.ToString()+",");
}
}
}
int start
= sb.ToString().LastIndexOf(",");
if (start
!= -1)
{
sb.Remove(start, 1);
}
sb.Append("}]");
return
sb.ToString();
}
}
}
========================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
namespace VincentLinq
{
///
/// 版本:1.0.1
///
用于将object,list,string,datatable等转换为json对象的类
/// 作者:Vincent 2012年9月8日
19:49:27
///
public class
JSONHelper
{
///
/// 将DataTable对象转换为json对象
///
/// DataTable对象
/// json格式的字符串
public static string
ConvertDataTableToJSON(DataTable dt)
{
System.Text.StringBuilder sb = new
System.Text.StringBuilder("[");
foreach
(DataRow row in dt.Rows)
{
sb.Append("{");
foreach (DataColumn col in
dt.Columns)
{
if (row.IsNull(col.ColumnName) == false)
{
if
(col.DataType != typeof(int) && col.DataType !=
typeof(float) && col.DataType != typeof(decimal) &&
col.DataType != typeof(double))
{
string str =
row[col.ColumnName].ToString();
str = str.Replace("[",
"【")
.Replace("]", "】")
.Replace(".", "。")
.Replace("{", "{")
.Replace("}", "}")
.Replace("\", "\\\")
.Replace(",", ",")
.Replace("\'", "‘")
.Replace(""", "”")
.Replace("\n", "")
.Replace("\r","")
.Replace("\n\r","")
.Replace(":", ":")
.Replace("-", "_")
.Replace("(", "(")
.Replace(")", ")")
.Replace("
","")
.Replace("
","")
.Replace("\t","");
sb.Append(""" +
col.ColumnName + "":"" + str + """);
}
else
{
string str =
row[col.ColumnName].ToString();
sb.Append(""" +
col.ColumnName + "":" + str);
}
}
else
sb.Append(""" + col.ColumnName + "":" + "");
sb.Append(",");
}
sb.Remove(sb.ToString().LastIndexOf(","),
1);//移除最后一个逗号,保证[{"col1":"lie","col2":"lie2"
sb.Append("},");//保证此时为[{"col1":"lie","col2":"lie2"},
}
//
sb.Remove(sb.ToString().LastIndexOf(","),
1);//保证此时为[{"col1":"lie","col2":"lie2"},{"col4":"lie","col5":"lie2"}
int start1
= sb.ToString().LastIndexOf(",");
if (start1
!= -1)
sb.Remove(start1,
1);//去除最后一个,
sb.Append("]");
return
sb.ToString();
}
///
/// 将集合转换为JSON
///
/// 类型
/// 集合对象
/// JSON对象
public static string
ConvertListToJSON(IEnumerable list) where T : new()
{
int
start1;
System.Text.StringBuilder sb = new
System.Text.StringBuilder("[");
foreach (T
t in list)
{
sb.Append("{");
Type type =
t.GetType();
PropertyInfo[] props =
type.GetProperties();
foreach (PropertyInfo p in
props)
{
object[] obj =
p.GetCustomAttributes(typeof(VincentLinqColumnAttribute),
false);
if (obj.Count() > 0)
{
VincentLinqColumnAttribute field = obj[0] as
VincentLinqColumnAttribute;
if (field
!= null)
{
string attrName =
field.ColumnName;
object attrValue =
p.GetValue(t, null);
if (attrValue == null)
{
sb.Append(""" + attrName + "":"" + null +
"",");
}
else if (attrValue is string
|| attrValue is DateTime)
{
string value = attrValue.ToString();
value = value.Replace(""", "“")
.Replace("\", "\\\")
.Replace(":", ":")
.Replace("\'", "’")
.Replace("\n", "")
.Replace("\r", "")
.Replace("\n\r", "");
sb.Append(""" + attrName + "":"" + value +
"",");
}
else
{
sb.Append(""" + attrName + "":" +
attrValue.ToString()+",");
}
}
}
//sb.Append(",");这地方append逗号会生成错误json,当有属性没有添加特性的时候会有bug
}
start1 =
sb.ToString().LastIndexOf(",");
if (start1 != -1)
{
sb.Remove(start1, 1);
}
sb.Append("},");
}
start1 =
sb.ToString().LastIndexOf(",");
if (start1
!= -1)
{
sb.Remove(start1, 1);
}
sb.Append("]");
return
sb.ToString();
}
///
/// 根据传入的对象获得该对象对应的JSON
///
/// 实体对象
/// JSON
public static string ConvertObjectToJSON(object
target)
{
Type type
= target.GetType();
PropertyInfo[] props = type.GetProperties();
System.Text.StringBuilder sb = new
System.Text.StringBuilder("[{");
foreach
(PropertyInfo p in props)
{
object[] objs =
p.GetCustomAttributes(typeof(VincentLinqColumnAttribute),
false);
if (objs.Count() >
0)
{
VincentLinqColumnAttribute field = objs[0] as
VincentLinqColumnAttribute;
string attrName = field.ColumnName;
object attrValue = p.GetValue(target,
null);
if (attrValue == null)
{
sb.Append(""" + attrName + "":"" + null + "",");
}
else if (attrValue is string || attrValue is
DateTime)
{
string
value = attrValue.ToString();
value =
value.Replace(""", "“")
.Replace("\", "\\\")
.Replace(":", ":")
.Replace("\'", "’")
.Replace("\n", "")
.Replace("\r", "")
.Replace("\n\r", "");
sb.Append(""" + attrName + "":"" + value + "",");
}
else
{
sb.Append(""" + attrName + "":" +
attrValue.ToString()+",");
}
}
}
int start
= sb.ToString().LastIndexOf(",");
if (start
!= -1)
{
sb.Remove(start, 1);
}
sb.Append("}]");
return
sb.ToString();
}
}
}
相关文章推荐
- ASP.NET MVC HtmlHelper 类的扩展方法
- 使用RouteValueDictionary简化对Asp.net MVC Helper的扩展
- ASP.NET MVC 使用总结(二)——扩展HtmlHelper实现动态生成title及meta
- ASP.NET中实现JSON和对象及集合之间互转,附JsonHelper辅助操作类
- asp.net JSONHelper JSON帮助类
- asp.net(c#)快速生成Json格式的数据(JsonHelper)
- dhl: 在 ASP.NET MVC 中创建自定义 HtmlHelper 使用扩展方法创建 HTML Helper
- Asp.net MVC Preview 4 中自定义Jquery的HtmlHelper扩展
- asp.net MVC添加HtmlHelper扩展示例和用法
- Asp.net MVC Preview 4 中自定义Jquery的HtmlHelper扩展
- ASP.NET MVC 使用总结(二)——扩展HtmlHelper实现动态生成title及meta
- Asp.Net MVC以 JSON传值扩展方法
- [ASP.NET MVC]为HtmlHelper添加一个RadioButtonList扩展方法
- ASP.Net MVC开发基础学习笔记:二、HtmlHelper与扩展方法
- JSonHelper.cs 用于ExtJS序列化对象 json.asp的Asp.Net版
- ASP.Net MVC开发基础学习笔记(2):HtmlHelper与扩展方法
- [ASP.NET MVC]通过对HtmlHelper扩展简化“列表控件”的绑定
- [ASP.NET MVC]通过对HtmlHelper扩展简化“列表控件”的绑定
- ASP.NET之JSONHelper操作
- 转:ASP.NET MVC扩展之HtmlHelper辅助方法