Json.Net学习笔记(七) 序列化集合
时间:2011-06-11 来源:资源收集
Json序列化器为序列化及反序列化集合对象提供了良好的支持.
->Serializing
为了序列化一个集合---一个泛型的list,array,dictionary,或者自定义集合---简单地调用序列化器,使用您想要进行序列化的集合对象作为参数,Json.Net会序列化集合以及所有它包含的值。
示例:
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
[JsonConverter(typeof(IsoDateTimeConverter))]
public DateTime ExpiryDate { get; set; }
}
测试:
Product p1 = new Product()
{
Name = "Product 1",
Price = 99.95m,
ExpiryDate = new DateTime(2010, 12, 19, 0, 0, 0, DateTimeKind.Utc)
};
Product p2 = new Product
{
Name = "Product 2",
Price = 12.50m,
ExpiryDate = new DateTime(2011, 1, 1, 0, 0, 0, DateTimeKind.Utc)
};
List<Product> products = new List<Product>();
products.Add(p1);
products.Add(p2);
string json = JsonConvert.SerializeObject(products, Formatting.Indented);
Console.WriteLine(json);
输出结果:
[
{
"Name": "Product 1",
"Price": 99.95,
"ExpiryDate": "2010-12-19T00:00:00Z"
},
{
"Name": "Product 2",
"Price": 12.50,
"ExpiryDate": "2011-01-01T00:00:00Z"
}
]
->Deserializing
为了反序列化Json到一个.Net集合中,只要指定一个您想要反序列化的集合类型就可以了,Json.Net支持多种类型的集合.
示例:
string json2 = @"[
{
""Name"": ""Product 1"",
""ExpiryDate"": ""2010-12-19T00:00:00Z"",
""Price"": 99.95,
""Sizes"": null
},
{
""Name"": ""Product 2"",
""ExpiryDate"": ""2011-01-01T00:00:00Z"",
""Price"": 12.50,
""Sizes"": null
}
]";
List<Product> productList = JsonConvert.DeserializeObject<List<Product>>(json2);
Console.WriteLine(productList.Count);//2
Product product1 = productList[0];
Console.WriteLine(product1.Name);//Product 1
->Deserializing Dictionaries
使用Json.Net你也可以反序列化一个Json对象到一个.Net的泛型Dictionary中.Json对象的属性名和属性值将会被添加到Dictionary中.
示例:
string jsonDictionary = @"{""key1"":""value1"",""key2"":""value2""}";
Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonDictionary);
Console.WriteLine(dic.Count);//2
Console.WriteLine(dic["key1"]);//value1