谷歌的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 "color: #ff0000">js客户端获取时间戳:var dt= new Date().getTime();以上这篇Jil,高效的json序列化和反序列化库就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。