ASP.NET MVCでJSONのプロパティをLowerCaseで返す方法
ASP.NET MVCでアプリケーションを作成しているときに
ちょっと困るのがAJAXでオブジェクトを取得したときに
プロパティがUpperCaseで返ってくることです。JavaScriptではLowerCaseで扱いたい><
今まではしょうがないって思ってたんですけどちょうどJavaScriptのリファクタリングをする必要があったので
C#側でLowerCaseで返すようにしてみました。
こんな感じのメソッドがあるとします。
クラスはMVCのControllerクラスを継承してAppControllerクラスを継承しています。
public class HomeController : AppController { public ActionResult GetData() { var model = new Model { ID = 1, Name = "佐藤" }; return Json(model, JsonRequestBehavior.AllowGet); } }
通常はこんな感じでそのまま頭大文字でJSONが返ります。
{"ID":1,"Name":"佐藤"}
頭を小文字に変更します。
まずMVCのJsonResultクラスを継承したAppJsonResultクラスを作成し
ExecuteResultメソッドをオーバーライドします。
ほとんどMVCのメソッドまるパクリなんですけどJSON文字列を生成するところだけ変更しています。
JSONの生成にはJson.NETを利用します。
public class AppJsonResult : System.Web.Mvc.JsonResult { 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) { var json = JsonConvert.SerializeObject( Data, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() } ); response.Write(json); } } }
AppControllerクラスでJsonResultメソッドをオーバーライドしてAppJsonResultを返すようにします。
public class AppController : Controller { protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior) { return new AppJsonResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding, JsonRequestBehavior = behavior }; } }
これでLowerCaseになったJSONを返すことができました。
{ "id": 1, "name": "佐藤" }
APIフレームワークだともっと簡単にできるみたいなんですけど
MVCだとなんかいい方法が見つからなかったんでこんな方法にしてみました。
まあこれから作るんだったらAPIの方で作れってことですね。