扩展方法ToJSON() 扩展方法ToJSON() and ParseJSON()
人气:0想了解扩展方法ToJSON() and ParseJSON()的相关内容吗,在本文为您仔细讲解扩展方法ToJSON()的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:ToJSON(),ParseJSON(),下面大家一起来学习吧。
使用例子: 复制代码 代码如下:
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);
}
}
}
加载全部内容