net自带JSON封装管理类[通用类]
时间:2011-01-29 来源:Stone_W
代码
using System;
/// <summary>
/// author:Stone_W
/// date:2011.1.29
/// desc:微软自带Json管理类封装
/// </summary>
public class MyJSONUtility
{
public MyJSONUtility() { }
#region 封装JSON
/// <summary>
/// 封装JSON
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="obj">封装为JSON的对象</param>
/// <returns>string</returns>
public static string GetJSON<T>(object obj)
{
string result = String.Empty;
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
serializer.WriteObject(ms, obj);
result = System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
}
catch (Exception ex)
{
throw ex;
}
return result;
}
#endregion
#region 把json还原为对象
/// <summary>
/// 把json还原为对象
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="jsonStr">json字符串</param>
/// <returns>T 对象类型</returns>
public static T ParseFormByJson<T>(string jsonStr)
{
T obj = Activator.CreateInstance<T>();
using (System.IO.MemoryStream ms =
new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonStr)))
{
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer =
new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
#endregion
}
相关阅读 更多 +