您的位置:首页 > 编程语言 > ASP

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

}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: