豚吐露@wiki

任意の形式に加工したJSONを返したい

最終更新:

Bot(ページ名リンク)

- view
管理者のみ編集可

任意の形式に加工したJSONを返したい

Windows 7 Professional
Visual Studio 2013 Professional
ASP.NET MVC5
ASP.NET Web API2

WebAPI2では、返す型をDictionary、Listにすると、勝手にJSONやXMLにしてくれる。

なので、こんな風に適当にDictionary、List、Arrayを組み合わせてobjectを作っても...
  1. public class HogeController : ApiController
  2. {
  3. public List<IDictionary<string, object>> Get()
  4. {
  5. IDictionary<string, Object>[] json = new Dictionary<string, Object>[2];
  6.  
  7. var child = new Dictionary<string, Object>();
  8.  
  9. child.Add("name", "ElementX");
  10.  
  11. var hList = new List<int>();
  12. for (int i = 0; i < 10; i++)
  13. {
  14. hList.Add(i);
  15. }
  16. child["データ"] = hList;
  17.  
  18. json[0] = child;
  19.  
  20. var grandchild1 = new Dictionary<string, Object>();
  21. grandchild1["p" + 1.ToString()] = "4";
  22. grandchild1["p" + 2.ToString()] = "9";
  23. grandchild1["p" + 3.ToString()] = "16";
  24. grandchild1["p" + 4.ToString()] = "25";
  25. grandchild1["p" + 5.ToString()] = "36";
  26. child["XX"] = grandchild1;
  27.  
  28. var child2 = new Dictionary<string, Object>();
  29.  
  30. child2["data"] = new []{ 2, 3, 6, 7, 11, 13, 17, 19, 23, 29, 31, 37 };
  31.  
  32. var grandchild2 = new List<string>();
  33. grandchild2.Add("あいうえお");
  34. grandchild2.Add("ABCDEFG");
  35. grandchild2.Add("АБВГДЕЁЖ");
  36. grandchild2.Add("ⅠⅡⅢⅣⅤⅥⅦ");
  37. grandchild2.Add("壱百弐拾参萬四阡五百六拾七");
  38.  
  39. child2.Add("ElementY", grandchild2);
  40.  
  41. json[1] = child2;
  42.  
  43. return json.ToList();
  44. }
  45. }

ちゃんとJSON形式で返してくれる。
中に突っ込まれてるArrayは、そのままでもちゃんとJSON化してくれるみたい。
  1. [
  2. {
  3. "XX": {
  4. "p1": "4",
  5. "p2": "9",
  6. "p3": "16",
  7. "p4": "25",
  8. "p5": "36"
  9. },
  10. "name": "ElementX",
  11. "データ": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  12. },
  13. {
  14. "ElementY": [
  15. "あいうえお",
  16. "ABCDEFG",
  17. "АБВГДЕЁЖ",
  18. "ⅠⅡⅢⅣⅤⅥⅦ",
  19. "壱百弐拾参萬四阡五百六拾七"
  20. ],
  21. "data": [2, 3, 6, 7, 11, 13, 17, 19, 23, 29, 31, 37]
  22. }
  23. ]

cf.) 参考までに、return前のjson objectの中身。



更新日: 2014年11月27日 (木) 13時53分28秒

名前:
コメント:

すべてのコメントを見る
添付ファイル
記事メニュー
ウィキ募集バナー