如何从ISO格式MVC4控制器返回JSON日期 [英] How to return json date from MVC4 controller in ISO format
问题描述
我使用Json.Net从ASP.NET MVC4控制器试图TRO归期ISO格式
I tried tro return date in ISO format using Json.Net from ASP.NET MVC4 controller
public JsonResult Sales() {
var saleList = new List<Sale>();
...
var str = JsonConvert.SerializeObject(saleList);
return Json(str, JsonRequestBehavior.AllowGet);
}
public class Sale
{
public DateTime saledate { get; set; }
...
}
但它返回整个对象JSON对象作为单个字符串。
But it returns whole object json notation as single string.
如何ISO格式为JSON对象返回日期?
How to return date in ISO format as json object ?
推荐答案
您可以用 ServiceStack做JSON序列化,但首先你必须将它集成到ASP.NET MVC。
You can do it with ServiceStack JSON serializer but first you have to integrate it to ASP.NET MVC.
安装包后,在应用程序启动配置日期时间序列化:
After installing the package, configure DateTime serialization in application start:
JsConfig.DateHandler = JsonDateHandler.ISO8601;
有关内容的JSON创建一个ActionResult类型:
Create an ActionResult type for JSON content:
public class CustomJsonResult : ActionResult
{
private readonly object _data;
private readonly string _content;
private readonly Encoding _encoding;
public CustomJsonResult(object data) : this(data, null, null) { }
public CustomJsonResult(object data, string content) : this(data, content, null) { }
public CustomJsonResult(object data, Encoding encoding) : this(data, null, encoding) { }
public CustomJsonResult(object data, string content, Encoding encoding)
{
_data = data;
_content = content;
_encoding = encoding;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(_content) ? "application/json" : _content;
if (_encoding != null)
{
response.ContentEncoding = _encoding;
}
response.Write(JsonSerializer.SerializeToString(_data));
}
}
然后你可以将这些方法添加到主控制器:
Then you can add these methods to a base controller:
protected CustomJsonResult CustomJson(object data)
{
return new CustomJsonResult(data);
}
protected CustomJsonResult CustomJson(object data, string content)
{
return new CustomJsonResult(data, content);
}
protected CustomJsonResult CustomJson(object data, Encoding encoding)
{
return new CustomJsonResult(data, encoding);
}
protected CustomJsonResult CustomJson(object data, string content, Encoding encoding)
{
return new CustomJsonResult(data, content, encoding);
}
最后,你可以返回这样的结果:
At last you can return the result like this:
return CustomJson(saleList);
这篇关于如何从ISO格式MVC4控制器返回JSON日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!