normalian blog

Let's talk about Microsoft Azure, ASP.NET and Java!

JSON Resultを返す

もう完全に単なる備忘録。DTO系のデータを入れ子にしたり、継承したり、リフレクションしたりは別途検討。
やっぱASP .NET MVC便利だよ。BtoC向けサービスならこっちの方が楽そう。

普通にIList系の結果を返す

  • Controller
    public class OtherResultController : Controller
    {
        public ActionResult JSonListTest()
        {
            IList<object> objCollection = new List<object>(){
                new { ID = 10, Name = @"みやびー" },
                new { ID = 11, Name = @"とのっち" },
                new { ID = 12, Name = @"しのしの" }
            };
            return new JsonResult() { Data = objCollection, ContentEncoding = System.Text.Encoding.UTF8, ContentType = @"application/json" };
        }
    }
  • JSONデータ
[{"ID":10,"Name":"みやびー"},{"ID":11,"Name":"とのっち"},{"ID":12,"Name":"しのしの"}]

普通にIDictionary系の結果を返す

  • Controller
    public class OtherResultController : Controller
    {
        public ActionResult JSonDictTest()
        {
            IDictionary<string, object> objCollection = new Dictionary<string, object>();
            objCollection.Add(new KeyValuePair<string, object>(@"みやびー", new { ID = 10, Name = @"みやびー" }));
            objCollection.Add(@"とのっち", new { ID = 11, Name = @"とのっち" });
            return new JsonResult() { Data = objCollection, ContentEncoding = System.Text.Encoding.UTF8, ContentType = @"application/json" };
        }
    }
  • JSONデータ
{"みやびー":{"ID":10,"Name":"みやびー"},"とのっち":{"ID":11,"Name":"とのっち"}}