I'm currently trying to use the Tree
class to build a tree-strucuture from a database query. Afterwards I want to convert it to a json object (with playframework api).
Some examples or a bit more documentation for the Tree
class would be awesome. I can't get my head arround the draw
and drawTree
method, which may do a similiar thing.
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))
This should result in a json tree like this
{
"name" : "Root",
"value" : 100,
"children" : [
{
"name" : "Category1",
"value": 30
},
{
"name": "Category2",
"value": 20,
"children" : [
{
"name" : "Sub1",
"value" : 15"
} ....
]
]
Writing a Writes
instance for this tree is quite possible:
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(_)))
)
}
}
This is quite a simple implementation and will show an empty children
array for the leaves, but that can no doubt be improved with a little extra work.
The drawTree
method is just for visualizing a tree, which is something else entirely:
scala> tree.drawTree
res2: String =
"("Root",100)
|
+- ("Category1",30)
|
+- ("Category2",20)
| |
| +- ("Sub1",15)
| |
| +- ("Sub2",3)
| |
| `- ("Sub3",2)
|
+- ("Category3",10)
|
`- ("Category4",30)
|
+- ("Sub1",20)
|
`- ("Sub2",5)
"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With