C# | .NET 4.5 | Entity Framework 5
我从 SQL 查询中获得的数据以 ID、ParentID 和 Name 的形式返回。我想将这些数据解析成分层的 JSON 字符串。迄今为止,这似乎是一个比应该更困难的任务。由于我使用了 Entity,数据作为 IEnumerable 很好地返回给我。现在我相信我只需要某种形式的递归,但我不太确定从哪里开始。任何帮助都会受到赞赏。
数据返回格式如下
id parentId name 1 1 TopLoc 2 1 Loc1 3 1 Loc2 4 2 Loc1A
代码如下
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": [
{}
]
}
]
}
Location loc = JsonConvert.DeserializeObject<Location>(json);
即可。 - Brian Rogers