JSON.NET(http://json.codeplex.com/,https://github.com/JamesNK/Newtonsoft.Json)使用來將.NET中的對象轉換為JSON字符串(序列化?),或者將JSON字符串轉換為.NET中已有類型的對象(反序列化?)
首先為了例子隨便定義一個類型:
public class Product { public string Name { get; set; } public DateTime Expiry { get; set; } public decimal Price { get; set; } public string[] Sizes { get; set; } public override string ToString() { return string.Format("Name:{0},Expiry:{1},Price:{2},SizesCount:{3}" , Name, Expiry, Price, Sizes.Length); } }
初始化對象:
public static void Main(string[] passwordargs) { Product product = new Product() { Name = "android", Expiry = DateTime.Now, Price = 2000, Sizes = new string[] { "1.5", "2.2", "4.1" } }; }
進行到JSON的轉換:
Console.WriteLine(JsonConvert.SerializeObject(product));
輸出結果:
{"Name":"android","Expiry":"2013-08-30T09:50:11.5147845+08:00","Price":2000.0,"Sizes":["1.5","2.2","4.1"]}
其它看起來一切正常,除了這個日期有點怪
格式化日期:
//設置日期時間的格式,與DataTime類型的ToString格式相同 IsoDateTimeConverter iso = new IsoDateTimeConverter(); iso.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; Console.WriteLine(JsonConvert.SerializeObject(product, iso));
輸出結果:
{"Name":"android","Expiry":"2013-08-30 09:53:58","Price":2000.0,"Sizes":["1.5","2.2","4.1"]}
從JSON到對象的轉換:
string str = "{\"Name\":\"android\",\"Expiry\":\"2013-08-30 09:53:58\",\"Price\":2000.0,\"Sizes\":[\"1.5\",\"2.2\",\"4.1\"]}"; Product p = (Product)JsonConvert.DeserializeObject(str, typeof(Product)); Console.WriteLine(p.ToString());
輸出結果:
Name:android,Expiry:2013/8/30 9:53:58,Price:2000.0,SizesCount:3
從JSON到鍵值對的轉換:
string strJson = @"{""Name1"": ""小明"",""Name2"": ""小花"",""Name3"": ""小紅""}"; Dictionary<string, string> _dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(strJson); foreach (KeyValuePair<string, string> kp in _dictionary) { Console.WriteLine(kp.Key + ":" + kp.Value); }
輸出結果:
Name1:小明
Name2:小花
Name3:小紅
從字符串轉換到JSON對象,以及JSON對象的簡單使用:
string strJson2 = @"{ ""student"": { ""Name1"": ""小明"" , ""Name2"": ""小花"" , ""Name3"": ""小紅""} }"; JObject jsonObj = JObject.Parse(strJson2); Console.WriteLine(jsonObj["student"]["Name1"].ToString()); Console.WriteLine(jsonObj["student"]["Name2"].ToString()); Console.WriteLine(jsonObj["student"]["Name3"].ToString());
輸出結果:
小明
小花
小紅
直接生成JSON對象:
JObject json = new JObject( new JProperty("Channel", new JObject( new JProperty("title", "JSON"), new JProperty("link", "JSON.NET"), new JProperty("description", "JSON.NET Description"), new JProperty("items", new JArray( new JObject(new JProperty("haha1", "123")), new JObject(new JProperty("haha2", "456")), new JObject(new JProperty("haha3", "789")) ))))); Console.WriteLine(json.ToString());
輸出結果:
{
"Channel": {
"title": "JSON",
"link": "JSON.NET",
"description": "JSON.NET Description",
"items": [
{
"haha1": "123"
},
{
"haha2": "456"
},
{
"haha3": "789"
}
]
}
}
暫時先記錄這么多,以后再繼續補充