我的webapi返回的默认DateTime格式不是我想要的。 如何自定义?
答案 0 :(得分:0)
创建DateTime转换器类
public class DateTimeConverter : DateTimeConverterBase
{
public string DateTimeFormat { get; set; }
public DateTimeConverter()
{
this.DateTimeFormat = "MMM/dd/yyyy HH:mm"; //PUT HERE ANY FORMAT YOU NEED!
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader,
Type objectType, object existingValue,
Newtonsoft.Json.JsonSerializer serializer)
{
if (objectType == typeof(DateTime))
{
//SEE HERE WHY.
throw new NotSupportedException("DateTime not allowed");
}
else if (objectType == typeof(DateTimeOffset))
{
reader.Read();
reader.Read();
DateTime dt = (DateTime)reader.Value;
reader.Read();
reader.Read();
Int64 offsetinMin = (Int64)reader.Value;
DateTime utcTime = new DateTime(dt.AddMinutes(-offsetinMin).Ticks,
DateTimeKind.Utc);
reader.Read();
return new DateTimeOffset(utcTime, TimeSpan.FromMinutes(0));
}
else
return null;
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer,
object value,
Newtonsoft.Json.JsonSerializer serializer)
{
if (value is DateTime)
{
DateTime utcTime = (DateTime)value;
writer.WriteRawValue(String.Format("\"{0}\"",
((DateTime)utcTime.ToLocalTime()).ToString(this.DateTimeFormat)));
}
else if (value is DateTimeOffset)
{
DateTimeOffset offs = (DateTimeOffset)value;
writer.WriteRawValue(String.Format("\"{0} UTC({1:##})\"",
offs.ToString(this.DateTimeFormat), offs.Offset.Minutes));
}
}
}
将此功能添加到控制器
protected ActionResult WriteJson(object data, JsonRequestBehavior behavior)
{
HttpResponseBase response = ControllerContext.HttpContext.Response;
response.ContentType = "application/json";
using (JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting.Indented })
{
JsonSerializerSettings sett = new JsonSerializerSettings();
// THE CUSTOM FORMATTER
sett.Converters.Add(new DateTimeConverter());
JsonSerializer serializer = JsonSerializer.Create(sett);
serializer.Serialize(writer, data);
writer.Flush();
}
return null;
}
用法:
WriteJson(new { data = XYZObjects }, JsonRequestBehavior.AllowGet);