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

2021-04-30 02:27

阅读:377

标签: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


评论


亲,登录后才可以留言!