这篇文章主要介绍了Jil、json序列化和反序列化库的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
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序列化和反序列化库的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持编程网,关注编程网行业资讯频道,更多相关知识等着你来学习!