Asp.net-Mvc
如何從 ASP.NET MVC 控制器方法返回由 JSON.NET 序列化的 camelCase JSON?
我的問題是我希望通過來自 ASP.NET MVC 控制器方法的ActionResult返回 camelCased(而不是標準 PascalCase)JSON 數據,並由JSON.NET序列化。
例如,考慮以下 C# 類:
public class Person { public string FirstName { get; set; } public string LastName { get; set; } }預設情況下,當從 MVC 控制器以 JSON 形式返回此類的實例時,它將以下列方式序列化:
{ "FirstName": "Joe", "LastName": "Public" }我希望它被序列化(通過 JSON.NET)為:
{ "firstName": "Joe", "lastName": "Public" }我該怎麼做呢?
我在 Mats Karlsson 的部落格上找到了一個很好的解決方案。解決方案是編寫一個 ActionResult 的子類,通過 JSON.NET 序列化數據,將後者配置為遵循 camelCase 約定:
public class JsonCamelCaseResult : ActionResult { public JsonCamelCaseResult(object data, JsonRequestBehavior jsonRequestBehavior) { Data = data; JsonRequestBehavior = jsonRequestBehavior; } public Encoding ContentEncoding { get; set; } public string ContentType { get; set; } public object Data { get; set; } public JsonRequestBehavior JsonRequestBehavior { get; set; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."); } var response = context.HttpContext.Response; response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data == null) return; var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; response.Write(JsonConvert.SerializeObject(Data, jsonSerializerSettings)); } }然後在你的 MVC 控制器方法中使用這個類,如下所示:
public ActionResult GetPerson() { return new JsonCamelCaseResult(new Person { FirstName = "Joe", LastName = "Public" }, JsonRequestBehavior.AllowGet)}; }
或者,簡單地說:
JsonConvert.SerializeObject( <YOUR OBJECT>, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });例如:
return new ContentResult { ContentType = "application/json", Content = JsonConvert.SerializeObject(new { content = result, rows = dto }, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }), ContentEncoding = Encoding.UTF8 };