相思资源网 Design By www.200059.com
使用例子:
复制代码 代码如下:
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);
}
}
}
复制代码 代码如下:
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);
}
}
}
相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com
暂无扩展方法ToJSON() and ParseJSON()的评论...