json - Scalaz 树到 JSON

标签 json scala tree scalaz scalaz7

我目前正在尝试使用 Tree类从数据库查询构建树结构。之后我想将其转换为 json 对象(使用 playframework api)。
Tree 的一些示例或更多文档课会很棒。我无法理解 drawdrawTree方法,它可能会做类似的事情。

例子

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/

相关文章:

json - 转到模板 HTMLEscape json 数据,它显示 """问题

javascript - Laravel 5.5 - 从 JSON 对象数组为数据表创建列标题

java - 合并列表中的多个 JObject - Json4s

scala - 如何在 Scala 中将元组隐式转换为向量

scala - coreNLP 显着减慢了 Spark 作业的速度`

scala - Scala中的函数式编程示例

javascript - 使用 tree-model-js 异步遍历树

java - 使用 Spring 返回 XML 响应 Rest API

javascript - 从数组动态生成嵌套树对象

python-2.7 - Python 和 NLTK : How to analyze sentence grammar?