2012-10-05

[C#][ASP.net] 關於JSON 格式的序列化


先說自己笨..以前都直接看 http://json.org/ 發現下面有提供.net solution的JSON格式序列化library..
所以之前我都是使用http://james.newtonking.com/projects/json-net.aspx 的JSON.net

不過也不錯,所以之前Silverlight 中我都是使用此來做JSON序列化反序列化..
http://www.dotblogs.com.tw/junegoat/archive/2011/07/22/json-silverlight-facebook-graph-api-parse.aspx

但是..人生最厲害的就是這個but..
其實.net 3.5 之後就有提供了..JavaScriptSerializer 類別
所以現在根本就不需要任何library就可以做到JSON格式的序列化跟反序列化..

之前,有一陣子我都習慣使用binrary 做序列化,之後WebService 盛行,就開始使用XML做序列跟反敘列..
但是現在已經21世紀了,基本上JSON有比較容解讀的優點,但是又不像XML有點癡肥的狀況…
所以現在幾乎我做檔案序列化跟反序列化,都是使用JSON格式,不一定只單純於網路上面傳遞資料..
下面Sample我建立一個簡單的Class :

User.cs

using System;

using System.Collections.Generic;





namespace TestJsonSerialization

{

public class User

{

public string Name { get; set; }

public int Age { get; set; }

public DateTime Birth { get; set; }



public List<User> Friends { get; set; }



}

}


之後對於 User 這物件進行序列化..





//建立一User 實體

User userInfo = new User() { Name = "Donma", Age = 28, Birth = DateTime.Now };



//建立User.Friends

User donmaFriend1 = new User() { Name = "Bear", Age = 7, Birth = DateTime.Now };

User donmaFriend2 = new User() { Name = "Huli", Age = 12, Birth = DateTime.Now };

userInfo.Friends = new List<TestJsonSerialization.User>();

userInfo.Friends.Add(donmaFriend1);

userInfo.Friends.Add(donmaFriend2);



//序列化

System.Web.Script.Serialization.JavaScriptSerializer objSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();

ltlJson.Text = objSerializer.Serialize(userInfo);


序列化之後的JSON Code:




 

{"Name":"Donma","Age":28,"Birth":"\/Date(1335718215715)\/","Friends":[{"Name":"Bear","Age":7,"Birth":"\/Date(1335718215715)\/","Friends":null},{"Name":"Huli","Age":12,"Birth":"\/Date(1335718215715)\/","Friends":null}]} 


反序列化:
System.Web.Script.Serialization.JavaScriptSerializer objSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
User obj = objSerializer.Deserialize<User>(ltlJson.Text);




很簡單易懂,其實因為最近太常用,所以乾脆寫在blog上面簡單copy and paste.

Smaple Preview:



Code: