使用Jackson库从Scala中的mapFields创建JSON

时间:2018-08-15 18:02:43

标签: json scala jackson

query_results

            1->map["id"->"1","name"->"x1",categery->"A","value"->"Dummy1"]  

            2->map["id"->"2","name"->"x2",categery->"A","value"->"Dummy2"]

            3->map["id"->"3","name"->"x3",categery->"B","value"->"Dummy3"]
            4->map["id"->"4","name"->"x4",categery->"B","value"->"Dummy4"]
            5->map["id"->"5","name"->"x5",categery->"B","value"->"Dummy5"]
            6->map["id"->"6","name"->"x6",categery->"B","value"->"Dummy6"]

我正在尝试使用scala和jackson库从这些地图字段创建json文件

输出Json应该看起来像这样

{"Result":
    "A":
        {"x1":"Dummy1",
         "x2":"Dummy2"}
    "B":
        {"x1":"Dummy3",
         "x1":"Dummy4",
         "x1":"Dummy5",
         "x1":"Dummy6"
        }
}

到目前为止,我尝试过的是

root = mapper.createObjectNode
child = mapper.createObjectNode
categoryA = mapper.createObjectNode

for((row,i)<-query_results.get.zipWithIndex)
val mapfields = row._2
id = mapfields.get("id")
if(id==1)
{
val x1 = mapfields.get("value")
categoryA.put("x1",x1)
}
if(id==2)
{
val x2 = mapfields.get("value")
categoryA.put("x2",x2)
child.set("A",categoryA)
}
root.set("Result",child)

这是可行的,但是我有30行,如果按照这种方法,我需要编写30条if子句。我希望有人会引导我找到更简单的解决方案。

1 个答案:

答案 0 :(得分:0)

使用https://github.com/json4s/json4s(“ org.json4s” %%“ json4s-jackson”%“ 3.6.0”):

import org.json4s.jackson.JsonMethods._
import org.json4s.JsonDSL.WithBigDecimal._

object CreatingJsonFromMapfieldsInScala_5186406 extends App {
  val input = Map(
    1 -> Map("id" -> "1", "name" -> "x1", "categery" -> "A", "value" -> "Dummy1"),
    2 -> Map("id" -> "2", "name" -> "x2", "categery" -> "A", "value" -> "Dummy2"),
    3 -> Map("id" -> "3", "name" -> "x3", "categery" -> "B", "value" -> "Dummy3"),
    4 -> Map("id" -> "4", "name" -> "x4", "categery" -> "B", "value" -> "Dummy4"),
    5 -> Map("id" -> "5", "name" -> "x5", "categery" -> "B", "value" -> "Dummy5"),
    6 -> Map("id" -> "6", "name" -> "x6", "categery" -> "B", "value" -> "Dummy6")
  ).values

  val byCategory = input.groupBy(_("categery"))
  val projected = byCategory.mapValues(_.map(row => row("name") -> row("value")))
  println(projected)
  println(compact(render("result" -> projected)))
}