一、序列化日期设置
1. 序列化日期时的JSON日期格式化处理
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
DateTime date = new DateTime(2015, 12, 11);
string json = JsonConvert.SerializeObject(date);
Console.WriteLine(json);
string jsonMicrosoft = JsonConvert.SerializeObject(date, new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
});
Console.WriteLine(jsonMicrosoft);
}
}
}
2.序列化后的运行结果
二、DateFormatString序列化日期设置
1.创建一个DataTime列表,并序列化.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Serialization;
using GongHuiNewtonsoft.Json.Converters;
using System.Collections.Specialized;
namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
IList<DateTime> list = new List<DateTime>
{
new DateTime(2015,12,14,11,33,35,DateTimeKind.Utc),
DateTime.Now,
DateTime.Today
};
string json = JsonConvert.SerializeObject(list, new JsonSerializerSettings
{
DateFormatString = "d MMMM, yyyy HH:mm:ss",
Formatting = Formatting.Indented
});
Console.WriteLine(json);
}
}
}
2.运行的结果
三、DateFormatString反序列化日期设置
1.反序列化日期,这个反序列化日期,中间的分隔符与系统的日期分隔符一样。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;
using GongHuiNewtonsoft.Json.Serialization;
using GongHuiNewtonsoft.Json.Converters;
using System.Collections.Specialized;
namespace JSONDemo
{
class Program
{
static void Main(string[] args)
{
string json = @"[
'2015-12-11T00:00:00',
'2015-12-14 13:23:22'
]";
IList<DateTime> list = JsonConvert.DeserializeObject<IList<DateTime>>(json, new JsonSerializerSettings
{
DateFormatString = "yyyy-MM-dd HH:mm:ss"
});
foreach (DateTime datetime in list)
{
Console.WriteLine(datetime);
}
}
}
}
2.运行的结果
JSON源代码下载地址:http://download.youkuaiyun.com/detail/lovegonghui/9342751