使用例子:
复制代码 代码如下:
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);
}
}
}
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
狼山资源网 Copyright www.pvsay.com
暂无“扩展方法ToJSON() and ParseJSON()”评论...