【发布时间】:2013-10-08 19:27:51
【问题描述】:
C# | .NET 4.5 |实体框架 5
我有从 SQL 查询返回的 ID、ParentID、Name 形式的数据。我想获取该数据并将其解析为分层 JSON 字符串。到目前为止,这似乎是一项比应有的艰巨任务。由于我使用的是实体,因此数据作为 IEnumerable 很好地返回给我。现在我相信我只需要某种形式的递归,但我不太确定从哪里开始。任何帮助表示赞赏。
数据返回为
id parentId 名称 1 1 顶部位置 2 1 位置 1 3 1 位置 2 4 2 位置1A代码是
public static string GetJsonLocationHierarchy(long locationID)
{
using (EntitiesSettings context = new EntitiesSettings())
{
// IEnumerable of ID,ParentID,Name
context.GetLocationHierarchy(locationID);
}
}
我希望的最终结果是这样的:
{
"id": "1",
"parentId": "1",
"name": "TopLoc",
"children": [
{
"id": "2",
"parentId": "1",
"name": "Loc1",
"children": [
{
"id": "4",
"parentId": "2",
"name": "Loc1A",
"children": [
{}
]
}
]
},
{
"id": "3",
"parentId": "1",
"name": "Loc2",
"children": [
{}
]
}
]
}
【问题讨论】:
标签: c# json entity-framework json.net hierarchy