1. 程式人生 > >轉載:在ASP.net 3.5中 用JSON序列化對象(兩種方法)

轉載:在ASP.net 3.5中 用JSON序列化對象(兩種方法)

for pep 技術分享 contract arr static returns web memory

asp.net3.5中已經集成了序列化對象為json的方法。

1:System.Runtime.Serialization.Json;
2:System.Web.Script.Serialization兩個命名空間下的不同方法進行序列化和反序列化。

第一種方法:System.Runtime.Serialization.Json

技術分享 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);
}
}
}
public class topMenu
{
public string id { get; set; }
public string title { get; set; }
public string defaulturl { get; set; }
}
topMenu t_menu = new topMenu()
{
id = "1",
title = "全局",
defaulturl = "123456"
};
List<topMenu> l_topmenu = new List<topMenu>();
for (int i = 0; i < 3; i++)
{
l_topmenu.Add(t_menu);
}
Response.Write(JsonHelper.GetJson<List<topMenu>>(l_topmenu));
技術分享


輸出結果為:
[{"defaulturl":"123456","id":"1","title":"全局"},{"defaulturl":"123456","id":"1","title":"全局"},{"defaulturl":"123456","id":"1","title":"全局"}]

下面利用上面ParseFromJson方法讀取Json
輸出結果為:全局

string szJson = @"{""id"":""1"",""title"":""全局"",""defaulturl"":""123456""} ";
topMenu t_menu2 = JsonHelper.ParseFromJson<topMenu>(szJson);
Response.Write(t_menu2.title);


第二種方法:System.Web.Script.Serialization

(引用System.Web.Extensions.dll)還是用到上面方法中JSON屬性的類,序列化方式不一樣。

技術分享 topMenu t_menu = new topMenu()
{
id = "1",
title = "全局",
defaulturl = "123456"
};

List<topMenu> l_topmenu = new List<topMenu>();

for (int i = 0; i < 3; i++)
{
l_topmenu.Add(t_menu);
}

技術分享


下面用這種方式輸出:

JavaScriptSerializer jss = new JavaScriptSerializer();
Response.Write( jss.Serialize(l_topmenu ));


輸出結果是相同的

[{"defaulturl":"123456","id":"1","title":"全局"},{"defaulturl":"123456","id":"1","title":"全局"},{"defaulturl":"123456","id":"1","title":"全局"}]

JavaScriptSerializer中的Deserialize方法讀取Json

string szJson = @"{""id"":""1"",""title"":""全局"",""defaulturl"":""123456""} ";
topMenu toptabmenu = jss.Deserialize<topMenu>(szJson);
Response.Write( jss.Serialize(toptabmenu.title));


輸出結果為:全局

綜上:兩種方法個有好處。一個比較靈活。[ScriptIgnore] ,可以讓JSON序列化忽略它從而不輸出。不被序列化。

轉載:在ASP.net 3.5中 用JSON序列化對象(兩種方法)