Search code examples
jsonscalalift-json

Scala object to json string using lift-json


I have a scala class like

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
  }

}

How do I use lift-json lib to convert metrics object like below to a json string.

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

When I try like this val json = Extraction.decompose(coda), I get a empty json {}. Any insight on how to do a conversion from scala pojo to json will be helpful.


Solution

  • The documentation for decompose says:

    Decompose a case class into JSON

    What you have there is not a case class. Case classes are the "pojo" in scala. You don't need to write all that boilerplate.

    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)