过去我们使用JSON.net序列化一个对象,在asp.net3.5中已经集成了序列化对象为json的方法。
我们分别针对System.Runtime.Serialization.Json和System.Web.Script.Serialization两个命名空间下的不同方法进行序列化和反序列化。
System.Runtime.Serialization.Json
(在vs2008添加引用System.Runtime.Serialization 如果在非WEB项目下还需要引用System.ServiceModel.Web)
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);
}
}
}
System.Web.Script.Serialization
(引用System.Web.Extensions.dll)
JavaScriptSerializer jss = new JavaScriptSerializer();
Response.Write( jss.Serialize(l_topmenu ));
string szJson = @"{""id"":""1"",""title"":""全局"",""defaulturl"":""123456""} ";
topMenu toptabmenu = jss.Deserialize<topMenu>(szJson);
Response.Write( jss.Serialize(toptabmenu.title));
综上。两种方法个有好处。一个比较灵活。一个较简洁