Json数据序列化对象,及对象序列化为Json格式

View Code
public class JsonHelper
{
/// <summary>
/// 生成Json格式
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string GetJson<T>(T obj)
{
DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream stream = new MemoryStream())
{
json.WriteObject(stream, obj);
string szJson = Encoding.UTF8.GetString(stream.ToArray());
return szJson;
}
}
/// <summary>
/// 转换Json的Model对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="szJson"></param>
/// <returns></returns>
public static T ParseFromJson<T>(string szJson)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
return (T)serializer.ReadObject(ms);
}
}
/// <summary>
/// 根据Json获取Dictionary集合
/// </summary>
/// <param name="szJson"></param>
/// <returns></returns>
public static Dictionary<string, string> GetDictionaryFromJson(string szJson)
{
Dictionary<string, string> list = new Dictionary<string, string>();

System.Web.Script.Serialization.JavaScriptSerializer jsonConvert = new System.Web.Script.Serialization.JavaScriptSerializer();
list = jsonConvert.Deserialize<Dictionary<string, string>>(szJson);

return list;
}
}

 

posted @ 2012-02-03 15:48  南阳·源  阅读(454)  评论(0编辑  收藏  举报