反射应用的一个小DEMO【利用反射,自动将对象生成json字符串】
时间:2011-04-19 来源:RiverDeng
先贴代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
namespace ReflectionDemo
{
class Program
{
static void Main(string[] args)
{
User userInfo1 = new User(1, "ZhangQin");
User userInfo2 = new User(2, "DengJiang");
User userInfo3 = new User(3, "WeiWei");
List<User> userList = new List<User>();
userList.Add(userInfo1);
userList.Add(userInfo2);
userList.Add(userInfo3);
string json = userList.ToJSON();
Console.WriteLine(json);
Console.ReadLine();
}
}
class User
{
private int id;
private string name;
public User(int id, string name)
{
this.id = id;
this.name = name;
}
[ToJSONAtrribute]
public int Id
{
get { return this.id; }
set { this.id = value; }
}
[ToJSONAtrribute]
public string Name
{
get { return this.name; }
set { this.name = value; }
}
}
[AttributeUsage(AttributeTargets.Property, Inherited = false)]
public class ToJSONAtrribute : Attribute
{
public ToJSONAtrribute()
{
}
}
public static class ExensionJSON
{
public static string ToJSON<T>(this IEnumerable<T> source)
{
string returnValue = "";
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (T item in source)
{
sb.Append("{");
Type typeInfo = item.GetType();
PropertyInfo[] properties = typeInfo.GetProperties();
foreach (PropertyInfo property in properties)
{
object[] attrs = property.GetCustomAttributes(typeof(ToJSONAtrribute),false);
if (attrs != null)
{
foreach (ToJSONAtrribute attr in attrs)
{
if (attr != null)
{
sb.Append(string.Format("\"{0}\":\"{1}\",", property.Name, property.GetValue(item, null)));
}
}
}
}
sb.Append("},");
}
sb.Append("]");
returnValue = sb.ToString ();
returnValue = Regex.Replace(returnValue,@"(,)(}|])","$2");
return returnValue;
}
}
}
相关阅读 更多 +