zoukankan      html  css  js  c++  java
  • WebApi 返回小驼峰式 json 格式,并格式化日期

    from:http://blog.csdn.net/magiccops/article/details/42969363

      屏蔽默认返回xml格式:Global文件加:GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 

    在 WebApiConfig 类中增加方法ConfigureApi,并在 Register 方法最后调用一下    ConfigureApi(config);    

    增加一个实现IContentNegotiator 接口的类 JsonContentNegotiator

    详细如下:

     public static void ConfigureApi(HttpConfiguration config)

            {
                var jsonFormatter = new JsonMediaTypeFormatter();
                var settings = jsonFormatter.SerializerSettings;

                IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
                //这里使用自定义日期格式
                timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
                settings.Converters.Add(timeConverter);


                settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));   

            }


      public class JsonContentNegotiator : IContentNegotiator
        {
            private readonly JsonMediaTypeFormatter _jsonFormatter;


            public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
            {
                _jsonFormatter = formatter;
            }


            public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
            {
                var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
                return result;
            }
        }

  • 相关阅读:
    异常:调用链顺序
    日志分割建议
    java异常处理规范
    忽略字母大小写情况下统计字符出现的次数
    十六进制转化为十进制
    搜索(剪枝优化):HDU 5113 Black And White
    水题:HDU 5112 A Curious Matt
    综合(奇技淫巧):HDU 5118 GRE Words Once More!
    网络流(费用流)CodeForces 321B:Ciel and Duel
    数学(概率)CodeForces 626D:Jerry's Protest
  • 原文地址:https://www.cnblogs.com/94cool/p/4386440.html
Copyright © 2011-2022 走看看