谷歌的potobuf不說了,它很牛B,但是對客戶端對象不支持,比如JavaScript就讀取不了。
Jil很牛,比Newtonsoft.Json要快很多,且支持客戶端,此處只貼代碼:
using Jil;using System.Runtime.Serialization;[Serializable] class Employee { //[JilDirective(Name = "cid")] public int Id { get; set; } [IgnoreDataMember] public string Name { get; set; } [DataMember(Name = "kkl")] public string Address { get; set; } public Employee() { } //必須要有一個午餐的構造函數 public Employee(int EmployeeId, string Name) { this.Id = EmployeeId; this.Name = Name; } }var jsonString = string.Empty; using (var output = new StringWriter()) { JSON.Serialize(new Employee(666, "zhangsan"), output); Console.WriteLine(output); jsonString = output.ToString(); } using (var input = new StringReader(jsonString)) { //var result = JSON.DeserializeDynamic(jsonString); //var result = JSON.Deserialize<Employee>(jsonString); var result = JSON.Deserialize<Employee>(input); Console.WriteLine("id:{0},name:{1}", result.Id, result.Name); }
需要注意的是,反序列化的強類型對象必須要有無參的構造函數或者只有一個參數的構造函數。
Such a type should have one declared field or property, and default or single parameter constructor.
對于時間處理,默認是ISO8601方式,可通過配置修改:
Options _jilOptions = new Options( dateFormat: DateTimeFormat.MillisecondsSinceUnixEpoch, includeInherited: true, serializationNameFormat: SerializationNameFormat.CamelCase ); var output = JSON.Serialize(new { UserName = "jon", TradingPassword = "123456", ClientIp = "192.168.3.1", Origin = 1, time = DateTime.Now }, _jilOptions); Console.WriteLine(output); Console.WriteLine("----------------"); var pt = "1459481266695"; //時間戳 DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); //說明下,時間格式為13位后面補加4個"0",如果時間格式為10位則后面補加7個"0" long lTime = long.Parse(pt + (pt.Length == 13 ? "0000" : "0000000")); var dtResult = dtStart.Add(new TimeSpan(lTime)); //得到轉換后的時間 Console.WriteLine(dtResult); Console.WriteLine("----------------"); var _time = DateTime.Now.Ticks; Console.WriteLine(DateTime.Now.ToString()); Console.WriteLine("當前時間轉換后模式:---------------->"); var dt = DateTime.FromBinary(_time); //635951023596206937【注意,此處與】 Console.WriteLine(dt.ToLongDateString()); //2016年4月1日 Console.WriteLine(dt.ToLongTimeString()); //10:12:39 Console.WriteLine(dt.ToShortDateString()); //2016/4/1 Console.WriteLine(dt.ToShortTimeString()); //10:12 Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss")); //2016-04-01 10:12:39
輸入如下:
關于客戶端時間戳的js處理,可參閱此文:js時間戳和c#時間戳互轉方法(推薦)
var date = new Date(1459481266695);Y = date.getFullYear() + '-';M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';D = date.getDate() + ' ';h = date.getHours() + ':';m = date.getMinutes() + ':';s = date.getSeconds(); console.log(Y+M+D+h+m+s); VM307:9 2016-04-1 11:27:46
js客戶端獲取時間戳:
var dt= new Date().getTime();
以上這篇Jil,高效的json序列化和反序列化庫就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答