以前要轉(zhuǎn)json一般都是自己手工去寫(xiě),再不濟(jì)就是用Newtonsoft.Json.dll這個(gè)第三方的類(lèi)庫(kù)
今天突然發(fā)現(xiàn).NET4.0里面自帶了,這可真是一個(gè)偉大的發(fā)現(xiàn)
準(zhǔn)備工作 需要引用 System.Web.Extensions.dll 這個(gè)類(lèi)庫(kù) 命名空間: System.Web.Script.Serialization |
|
|
數(shù)據(jù)結(jié)構(gòu) public class Team { public string Name { get; set; } public List<User> Users { get; set; } } public class User { public int Id { get; set; } public string Name { get; set; } } |
|
Class --> JSON JavaScriptSerializer js = new JavaScriptSerializer(); Team team = new Team() { Name = "夢(mèng)之隊(duì)", Users = new List<User>() { new User() { Id = 1, Name = "XXX" }, new User() { Id = 2, Name = "YYY" }, new User() { Id = 3, Name = "ZZZ" }, } }; string json = js.Serialize(team); Console.WriteLine(json); 輸出結(jié)果
|
|
|
Json --> Class
string json =
"{\"Name\":\"夢(mèng)之隊(duì)\",\"Users\":[{\"Id\":1,\"Name\":\"XXX\"},{\"Id\":2,
\"Name\":\"YYY\"},{\"Id\":3,\"Name\":\"ZZZ\"}]}"; JavaScriptSerializer js = new JavaScriptSerializer(); Team team = js.Deserialize<Team>(json); 結(jié)果:
|
|