扩展方法ToJSON() and ParseJSON()
程序员文章站
2022-05-31 17:02:13
使用例子: 复制代码 代码如下: protected void Page_Load(object...
使用例子:
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);
}
}
}
上一篇: IBM加速转型:变身大数据“种子选手”
下一篇: 想要瘦腿怎么办,五种食物让你告别大象腿