標籤:des style blog http color java 使用 os
Json.Net是.net中的一種流行的高效能的JSON架構。
特點
- 靈活的JSON序列化轉化.net對象為JSON字串。和把JSON字串轉換為.net對象。
- 手動讀寫JSON的Linq to JSON
- 比.net內建的JSON序列化程式更高的效能和速度。
- 便於讀寫的JSON
- 從XML中讀取或寫入JSON
- 支援Silverlight和Windows phone.
當你讀寫的JSON與.net類緊密關聯時,JSON序列化程式是一個不錯的選擇。JSON序列化程式將自動讀寫相關類的JSON。
如果你只對JSON裡面的資料感興趣、你沒有與JSON相關聯的.net類或者JSON資料與你的類沒有任何關係,你需要從對象中手動讀寫資料。以上各種情況下,你可以使用LINQ To JSON. LINQ To JSON 允許你在.net中更容易的讀取、寫入、修改JSON資料。
Download Json.NET from CodePlex or install using NuGet。
PM> Install-Package Newtonsoft.Json
JSON.net列表
http://json.codeplex.com/releases/view/74287
提供JSON.NET 4.0 Release 3版本地址
http://json.codeplex.com/releases/view/74287#DownloadId=287841
更多JSON詳細資料,請查看: http://james.newtonking.com/projects/json-net.aspx
先構造一個簡單的類employee
Public class employee{ Public string eid{get;set;} Public string ename{get;set;} Public string esex{get;set;} Public datetime birthday{get;set;}}
JSON序列化與還原序列化的方案
- 使用Json.Net 處理JSON序列化與還原序列化
序列化方法private string JsonSerialize(employee emp) {return Newtonsoft.Json.JsonConvert.SerializeObject(emp);}還原序列化方法private employee JsonDeserialize(string json) {return (employee)(Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(employee)));}
- 使用JavaScriptSerializer進行序列化、還原序列化
序列化方法 private string JsonSerialize (employee emp) {return new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(emp);}還原序列化Private string JsonDeserialize (string json){return (employee)(new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(json,typeof(employee)));}
- 通過類DataContractJsonSerializer對JSON序列化和還原序列化
序列化方法
private string JsonSerialize (employee emp) { System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); dcjs.WriteObject(ms, emp); string json = System.Text.Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return json; }
還原序列化方法
private employee JsonDeserialize (string json) { System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee)); System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));employee obj = (employee)(dcjs.ReadObject(ms));return obj; }
- 通過Newtonsoft.Json.Linq.JObject擷取JSON資料
private void LinqJson(string json) {JObject obj = Newtonsoft.Json.Linq.JObject.Parse(json);//擷取全部資料值foreach (JToken token in obj.Values()) {Response.Write(token.ToString());}//擷取唯一值Response.Write(obj["eid"].ToString()+"<br />"); }
- 5、LINQ to JSON Example
string json = @"{ ""Name"": ""Apple"", ""Expiry"": new Date(1230422400000), ""Price"": 3.99, ""Sizes"": [ ""Small"", ""Medium"", ""Large"" ]}";JObject o = JObject.Parse(json);string name = (string)o["Name"];// AppleJArray sizes = (JArray)o["Sizes"];string smallest = (string)sizes[0];
JSON序列化和還原序列化日期時間的處理
JSON格式不直接支援日期和時間。DateTime值值顯示為"/Date(700000+0500)/"形式的JSON字串,其中第一個數字(在提 供的樣本中為 700000)是 GMT 時區中自 1970 年 1 月 1 日午夜以來按正常時間(非夏令時)經過的毫秒數。該數字可以是負數,以表示之前的時間。樣本中包括"+0500"的部分可選,它指示該時間屬於Local 類型,即它在還原序列化時應轉換為本地時區。如果沒有該部分,則會將時間還原序列化為Utc。
使用DataContractJsonSerializer的序列化方式對日期格式進行處理,其他的(反)序列化方案的使用方式是相同的。設計思想是通過Regex匹配,替換JSON裡面的日期資料為正常的日期格式。
序列化方法
private string JsonSerialize (employee emp) {System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee));System.IO.MemoryStream ms = new System.IO.MemoryStream();dcjs.WriteObject(ms, emp);string json = System.Text.Encoding.UTF8.GetString(ms.ToArray());ms.Close();//替換JSON時間為字串string p = @"\\/Date\((\d+)\)\\/";System.Text.RegularExpressions.MatchEvaluator me = new System.Text.RegularExpressions.MatchEvaluator(ConvertJsonDateToDataString);System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(p);json = regex.Replace(json, me);return json;} private string ConvertJsonDateToDataString(System.Text.RegularExpressions.Match m) {string result = string.Empty;DateTime dt = new DateTime(1970,1,1);dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));dt = dt.ToLocalTime();result = dt.ToString("yyyy-MM-dd HH:mm:ss");return result;}
還原序列化方法
private employee JsonDeserialize (string json){string p = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";System.Text.RegularExpressions.MatchEvaluator me = new System.Text.RegularExpressions.MatchEvaluator(ConvertDateStringToJsonDate);System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(p);json = reg.Replace(json, me); System.Runtime.Serialization.Json.DataContractJsonSerializer dcjs=new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(employee));System.IO.MemoryStream ms=new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));employee emp=(employee)dcjs.ReadObject(ms);return emp;} private string ConvertDateStringToJsonDate(System.Text.RegularExpressions.Match m){string result = string.Empty;DateTime dt = DateTime.Parse(m.Groups[0].Value);dt = dt.ToUniversalTime();TimeSpan ts = dt - DateTime.Parse("1970-1-1");result = string.Format("\\/Date({0}+0800)\\/", ts.TotalMilliseconds);return result;}