using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
/// <summary>
/// Generic 的摘要说明
/// </summary>
public class Generic<T>
{
public string GetJsonData(T item)
{
string json = "[{";
PropertyInfo[] properties = item.GetType().GetProperties();
foreach (PropertyInfo proInfo in properties)
{
json += proInfo.Name + ":/"" + proInfo.GetValue(item, null).ToString() + "/",";
}
json = json.Substring(0, json.Length - 1);
json += "}]";
return json;
}
public string GetJsonData(List<T> item)
{
string json = "[";
foreach(T t in item)
{
json += "{";
PropertyInfo[] properties = t.GetType().GetProperties();
foreach (PropertyInfo proInfo in properties)
{
json += proInfo.Name + ":/"" + proInfo.GetValue(t, null).ToString() + "/",";
}
json = json.Substring(0, json.Length - 1);
json += "},";
}
json = json.Substring(0, json.Length - 1);
json += "]";
return json;
}
}
目前支持普通类和List的数据格式。
本文介绍了一个C#中的泛型类,该类能够将任意类型的数据转换为JSON格式。支持单个对象及列表的转换,利用反射获取对象属性并构造JSON字符串。
1769

被折叠的 条评论
为什么被折叠?



