使用lift-json

时间:2015-10-15 23:35:35

标签: json scala lift-json

我有像

这样的scala类
class metrics{
  private var _moduleId: String = ""
  private var _blah1: String = ""
  private var _metadata: Map[String, String] = Map()

  def moduleId: String = _moduleId

  def moduleId_(value: String): Unit = {
    _moduleId = value
  }

  def blah1: String = _blah1

  def blah1_(value: String): Unit = {
    _blah1 = value
  }

  def metadata: Map[String, String] = _metadata

  def metadata_(value: Map[String, String]): Unit = {
    _metadata = value
  }

}

如何使用lift-json lib将下面的度量对象转换为json字符串。

val coda = new metrics()
    coda.blah1_("blah1")
    coda.moduleId_("module1")
    coda.metadata_(Map("p1"->"Alice","p2"->"Bob"))

当我尝试这样val json = Extraction.decompose(coda)时,我得到一个空的json {}。有关如何从scala pojo转换为json的任何见解都会有所帮助。

1 个答案:

答案 0 :(得分:1)

decompose的文档说:

  

将案例类分解为JSON

你所拥有的不是案例类。案例类是" pojo"在斯卡拉。你不需要编写所有样板文件。

case class Metrics(moduleId: String = "", blah1: String = "", metadata: Map[String, String] = Map())

val coda = Metrics(
  blah1 = "blah1",
  moduleId = "module1",
  metadata = Map("p1"->"Alice","p2"->"Bob"))

val json = Extraction.decompose(coda)