我目前正在尝试使用 Tree
类从数据库查询构建树结构。之后我想将其转换为 json 对象(使用 playframework api)。Tree
的一些示例或更多文档课会很棒。我无法理解 draw
和 drawTree
方法,它可能会做类似的事情。
例子
val tree = ("Root", 100).node(
("Category1", 30).leaf,
("Category2", 20).node(
("Sub1", 15).leaf,
("Sub2", 3).leaf,
("Sub3", 2).leaf),
("Category3", 10).leaf,
("Category4", 30).node(
("Sub1", 20).leaf,
("Sub2", 5).leaf))
这应该会产生一个像这样的 json 树
{
"name" : "Root",
"value" : 100,
"children" : [
{
"name" : "Category1",
"value": 30
},
{
"name": "Category2",
"value": 20,
"children" : [
{
"name" : "Sub1",
"value" : 15"
} ....
]
]
最佳答案
写一个 Writes
这棵树的实例很有可能:
import scalaz.Tree, Tree.Node
implicit def treeWrites: Writes[Tree[(String, Int)]] =
new Writes[Tree[(String, Int)]] {
def writes(o: Tree[(String, Int)]) = o match {
case Node((name, value), children) => Json.obj(
"name" -> name,
"value" -> value,
"children" -> JsArray(children.map(Json.toJson(_)))
)
}
}
这是一个非常简单的实现,将显示一个空的
children
叶子的数组,但毫无疑问可以通过一些额外的工作来改进。
关于json - Scalaz 树到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20165957/