标记: ServiceStack.Text,json,序列化,日期
在使用ServiceStack.Text的序列化为json格式的时候,当属性为datetime的时候,返回的是一个new date(324234234)的字符串,看着非常不爽。 如果是js来获取结果还好,
如果是c#获取这种字符串是没有办法转化为时间的。 所以我改造了下,让返回的是‘2015-06-06 09:11:11’的格式。
先获取源码, 然后在jsconfig.cs中加入如下代码
Code Snippet
- private static bool dMsDatetimeFormat=true;
- ??????public static bool MsDatetimeFormat
- ??????{
- ??????????get { return dMsDatetimeFormat; }
- ??????????set { dMsDatetimeFormat = value; }
- ??????}
这是用来标示是否转化为刚才看到的那种自定义的格式。
接着 修改DateTimeSerializer.cs文件的 public static void WriteWcfJsonDate(TextWriter writer, DateTime dateTime)方法
修改后的代码如下
Code Snippet
- public static void WriteWcfJsonDate(TextWriter writer, DateTime dateTime)
- ????{
- ????????if (JsConfig.AssumeUtc && dateTime.Kind == DateTimeKind.Unspecified)
- ????????{
- ????????????dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
- ????????}
- ????????if (JsConfig.DateHandler == DateHandler.ISO8601)
- ????????{
- ????????????writer.Write(dateTime.ToString("o", CultureInfo.InvariantCulture));
- ????????????return;
- ????????}
- ????????if (JsConfig.DateHandler == DateHandler.RFC1123)
- ????????{
- ????????????writer.Write(dateTime.ToUniversalTime().ToString("R", CultureInfo.InvariantCulture));
- ????????????return;
- ????????}
- ????????var timestamp = dateTime.ToUnixTimeMs();
- ????????string offset = null;
- ????????if (dateTime.Kind != DateTimeKind.Utc)
- ????????{
- ????????????if (JsConfig.DateHandler == DateHandler.TimestampOffset && dateTime.Kind == DateTimeKind.Unspecified)
- ????????????????offset = UnspecifiedOffset;
- ????????????else
- ????????????????offset = LocalTimeZone.GetUtcOffset(dateTime).ToTimeOffsetString();
- ????????}
- ????????else
- ????????{
- ????????????// Normally the JsonDateHandler.TimestampOffset doesn't append an offset for Utc dates, but if
- ????????????// the JsConfig.AppendUtcOffset is set then we will
- ????????????if (JsConfig.DateHandler == DateHandler.TimestampOffset && JsConfig.AppendUtcOffset.HasValue && JsConfig.AppendUtcOffset.Value)
- ????????????????offset = UtcOffset;
- ????????}
- ????????if (JsConfig.MsDatetimeFormat)
- ????????{
- ????????????writer.Write(dateTime.ToString("yyyy-MM-dd hh:mm:ss"));
- ????????}
- ????????else
- ????????{
- ????????????writer.Write(EscapedWcfJsonPrefix);
- ????????????writer.Write(timestamp);
- ????????????if (offset != null)
- ????????????{
- ????????????????writer.Write(offset);
- ????????????}
- ????????????writer.Write(EscapedWcfJsonSuffix);
- ????????}
- ????}
这样再使用序列化方法的时候返回的就是’2015-09-08 11:11:11’的格式了
Code Snippet
- ServiceStack.Text.JsonSerializer.SerializeToString(new
- ????????????????{???date=DateTime.Now,
- ????????????????????SecureContent = "here's some secure content that you can only see if you provide a correct apiKey",
- ????????????????????User = "user"
- ????????????????})
当你不想用的时候,想恢复默认的方式,只要序列化前用这句就行了
ServiceStack.Text.JsConfig.MsDatetimeFormat = false;
标记: ServiceStack.Text,json,序列化,日期
时间: 2024-10-03 13:45:19