Scalaz Tree to JSON
json, scala, scalaz, scalaz7, tree
Solution
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.
Problem
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. Example ``` 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" } .... ] ] ```