码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET JsonResult返回日期格式及首字母大写解决

时间:2021-04-28 12:07:11      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:form   time   code   serialize   tip   throw   pre   void   vat   

添加一个类继承JsonResult

  public class CustomJsonResult : JsonResult
    {
        private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

        public CustomJsonResult()
        {
            serializerSettings = new JsonSerializerSettings
            {
                // 设置为驼峰命名
                ContractResolver = new CamelCasePropertyNamesContractResolver(), //首字母小写
                DateFormatString = _dateFormat   //日期格式

             };
        }
        private JsonSerializerSettings serializerSettings { get; set; }
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            if (!String.IsNullOrEmpty(ContentType))
            {
                response.ContentType = ContentType;
            }
            else
            {
                response.ContentType = "application/json";
            }
            if (ContentEncoding != null)
            {
                response.ContentEncoding = ContentEncoding;
            }
            if (Data != null)
            {
                // Using Json.NET serializer                     
                var sctiptSerialize = JsonSerializer.Create(serializerSettings);    
                sctiptSerialize.Serialize(response.Output, Data);
            }
        }

调用:

 public ActionResult Test()
        {
            Person p = new Person() { Name = "zhangsan", Age = 1, BirthDay = DateTime.Now };
            //return Json(d);
            return new CustomJsonResult {Data=p };
        }

 

ASP.NET JsonResult返回日期格式及首字母大写解决

标签:form   time   code   serialize   tip   throw   pre   void   vat   

原文地址:https://www.cnblogs.com/Zingu/p/14711100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!