定義合約:
var postContract = new JsonContract<Post>(); postContract.SimpleProperty(p => p.Title); postContract.SimpleProperty(p => p.CreateTime).Converter(new DataTimeConverter());
在這里,DataTimeConverter會(huì)將CreateTime屬性的時(shí)間日期轉(zhuǎn)化為字符串以后再輸出。例如:
var post = new Post { Title = "Good day today.", CreateTime = DateTime.Now }; Console.WriteLine(JsonSerializer.SerializeObject(post, postContract)); Console.WriteLine();
便會(huì)得到:
{ "Title" : "Good day today.", "CreateTime" : "Sun, 10 Oct 2010 23:12:53 GMT" }
我們可以做得還有更多,例如這里有一個(gè)包含復(fù)雜屬性的Category對(duì)象:
public class Category { public string Name { get; set; } public User Author { get; set; } public List<Post> Posts { get; set; } }
我們?cè)诙xCategory的合約時(shí),則可以用到之前的合約:
var categoryContract = new JsonContract<Category>(); categoryContract.SimpleProperty(p => p.Name); categoryContract.ComplexProperty(p => p.Author).Contract(userContract); categoryContract.ArrayProperty(p => p.Posts).ElementContract(postContract);
那么下面這段代碼:
var category = new Category { Name = "Default", Author = new User { UserName = "Jerry", Age = 15 }, Posts = new List<Post> { new Post { Title = "Post 1", CreateTime = new DateTime(2010, 1, 1) }, new Post { Title = "Post 2", CreateTime = new DateTime(2010, 2, 1) }, new Post { Title = "Post 3", CreateTime = new DateTime(2010, 3, 1) } } }; var jsonCategory = JsonSerializer.SerializeObject(category, s_categoryContract); Console.WriteLine(jsonCategory);
出處:老趙點(diǎn)滴
責(zé)任編輯:bluehearts
上一頁(yè) 輕量級(jí)JSON映射類(lèi)庫(kù) [2] 下一頁(yè) 輕量級(jí)JSON映射類(lèi)庫(kù) [4]
◎進(jìn)入論壇網(wǎng)絡(luò)編程版塊參加討論
|