使用例子:
代码如下:
protected void Page_Load(object sender, EventArgs e)
{
Person p = new Person
{
Name = "wuchang",
Email = "wuchangx@qq.com",
LastActive = DateTime.Now,
Arr = new string[] { "arr1", "arr2" },
Lst = new List<string>( new string[] { "lst1", "lst2" } )
};
string json = p.ToJSON();
this.TextBox1.Text = json;
Person pp = json.ParseJSON<Person>();
this.TextBox2.Text = pp.ToJSON();
}
实现
代码如下:
public static class JSONExtension
{
public static string ToJSON(this object obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
public static T ParseJSON<T>(this string str)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(str)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
}