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 }; }