@monamonamonapiii0425 (na mo)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Asp.Net WebAPIで階層構造のデータを返却したい

ASP.NET WebAPI(.NET framework) のGetメソッド(HttpGet)でDBから取得した情報を下記のような階層構造に変換し一旦クラスに格納。そのクラスのデータをクライアントに返却したいです。
クラスの設計はAクラスのメンバーにDictionaryといった形で親クラスに小クラスのメンバーを配置しています。(クラスにはdatacontract属性をつけています)
しかし、 返却されるのはAクラスの要素のみでB,Cクラスの要素は何もデータがありません。この辺にお詳しい方が周りにいないためここで質問させて頂きます。どうぞよろしくお願いします。

※最終的にはツリービューに表示するデータ
■データ(クラス)の構造
  A
 -|B-1
  -|C-1
  -|C-2
  -|C-3
 -|B-2
  -|C-1
  -|C-2
  A-1
 -|B-1
  -|C-1
  -|C-2
  -|C-3
 -|B-2
  -|C-1
  -|C-2

0 likes

1Answer

ざっくり試しました。
下記にコードを記載しておきます。

AModel.cs
using System.Collections.Generic;

namespace WebApiSample0001.Models
{
    public class AModel
    {
        public string Value;
        public Dictionary<string, BModel> BList;
    }
}
BModel.cs
using System.Collections.Generic;

namespace WebApiSample0001.Models
{
    public class BModel
    {
        public string Value;
        public Dictionary<string, CModel> CList;
    }
}
CModel.cs
namespace WebApiSample0001.Models
{
    public class CModel
    {
        public string Value;
    }
}
TestController.cs
using System.Collections.Generic;
using System.Web.Http;
using WebApiSample0001.Models;

namespace WebApiSample0001.Controllers
{
    public class TestController : ApiController
    {
        [HttpGet]
        [Route("test")]
        public AModel Get()
        {
            CModel c1 = new CModel() { Value = "C-1" };
            CModel c2 = new CModel() { Value = "C-2" };
            CModel c3 = new CModel() { Value = "C-3" };

            BModel b1 = new BModel() { Value = "B-1", CList = new Dictionary<string, CModel>() };
            b1.CList.Add("1", c1);
            b1.CList.Add("2", c2);
            b1.CList.Add("3", c3);

            BModel b2 = new BModel() { Value = "B-2", CList = new Dictionary<string, CModel>() };
            b2.CList.Add("1", c1);
            b2.CList.Add("2", c2);

            AModel a1 = new AModel() { Value = "A-1",BList = new Dictionary<string, BModel>()};
            a1.BList.Add("1", b1);
            a1.BList.Add("2", b2);

            return a1;
        }
    }
}

出力結果(整形済み)
{
    "Value": "A-1",
    "BList": {
        "1": {
            "Value": "B-1",
            "CList": {
                "1": {
                    "Value": "C-1"
                },
                "2": {
                    "Value": "C-2"
                },
                "3": {
                    "Value": "C-3"
                }
            }
        },
        "2": {
            "Value": "B-2",
            "CList": {
                "1": {
                    "Value": "C-1"
                },
                "2": {
                    "Value": "C-2"
                }
            }
        }
    }
}

何かの参考になれば幸いです。

0Like

Your answer might help someone💌