c# MVC返回小驼峰Json(首字母小写)

1.与前端交互时,前端总希望传过去的json字段名首字母小写,但是.net规范是首字线大写

如果就写了下面的转换方法

/// <summary>
        /// Poco类字段名转换成首字母小写的字典
        /// 用于 MVC 的 new JsonResult(){Data=xxx} 后前端Javascript使用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static dynamic PocoToFirstCharLowerJsonResultData<T>(this T obj) where T : class
        {
            var objJson = obj.ToJson();
            var dict = objJson.ToInstance<Dictionary<string, object>>();

            return dict.ToDictionary(p => p.Key[0].ToString().ToLower() + p.Key.Substring(1), p => p.Value);
        }

        /// <summary>
        /// 普通类字段名转换成首字母小写的字典
        /// 用于 MVC 的 new JsonResult(){Data=xxx} 后前端Javascript使用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static dynamic ToFirstCharLowerJsonResultData<T>(this T obj) where T : class
        {
            var objJson = obj.ToJson();
            var rx = new Regex(@"""(?<v>(\w)*?)"":", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
            var match = rx.Match(objJson);
            while (match.Success)
            {
                var originalKeyName = match.Result("${v}");
                var currentKeyName = originalKeyName[0].ToString().ToLower() + originalKeyName.Substring(1);
                objJson = rx.Replace(objJson, "\"" + currentKeyName + "\":", 1, match.Index);
                match = match.NextMatch();
            }

            var dict = objJson.ToInstance<Dictionary<string, object>>();

            return dict.ToDictionary(p => p.Key[0].ToString().ToLower() + p.Key.Substring(1), p => p.Value);
        }

2.Controller调用如下

 public ActionResult QueryAllModels()
        {
            var response = this.Service.QueryModels();

            return new JsonResult(){Data=response .ToFirstCharLowerJsonResultData()};
        }

 

3.另一种实现,用 Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver

/// <summary>
    /// JsonResult,驼峰式转换
    /// </summary>
    public class LowerCamelJsonResult : ActionResult
    {
        /// <summary>
        /// 目标对象
        /// </summary>
        public object Data { get; set; }

        /// <summary>
        /// 构造器
        /// </summary>
        public LowerCamelJsonResult() { }

        /// <summary>
        /// 构造器
        /// </summary>
        public LowerCamelJsonResult(object data)
        {
            this.Data = data;
        }

        /// <summary>
        /// 重写执行结果
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            //json对象命名小驼峰式转换
            var json = JsonConvert.SerializeObject(
                this.Data,
                Formatting.Indented,
                new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }
                );

            context.HttpContext.Response.Write(json);
        }
    }

 

调用方法

 public ActionResult QueryAllModels()
        {
            var response = this.Service.QueryModels();

            return new LowerCamelJsonResult(){Data=response };
        }

转载于:https://www.cnblogs.com/zhshlimi/p/6908001.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值