0
votes

I try to generate json by combining some fields, including a Seq of case class.

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.{read, write}

object JsonExample extends App {
  case class CC(eid: String, num: Integer)
  implicit val formats:Formats = Serialization.formats(NoTypeHints)

  val json = ("api_key" -> "1234") ~ ("attributes" -> List(CC("123", 123), CC("222", 222)))

  println(write(json))
}

But I got compilation errors

Error:(9, 36) No implicit view available from List[JsonExample.CC] => org.json4s.JsonAST.JValue. val json = ("api_key" -> "1234") ~ ("attributes" -> List(CC("123", 123), CC("222", 222)))

Error:(9, 36) not enough arguments for method ~: (implicit ev1: List[JsonExample.CC] => org.json4s.JsonAST.JValue)org.json4s.JsonAST.JObject. Unspecified value parameter ev1. val json = ("api_key" -> "1234") ~ ("attributes" -> List(CC("123", 123), CC("222", 222)))

Note, if I remove the combine ~, then it works: val json = ("attributes" -> List(CC("123", 123), CC("222", 222)))

Please help.

1

1 Answers

1
votes

You can see in "Extending the DSL" section, that if you want to add CC class support into the DSL you should provide implicit conversion type DslConversion = CC => JValue.

So, you should write something like this:

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.write

object JsonExample extends App {
    implicit val formats = Serialization.formats(NoTypeHints)

    case class CC(eid: String, num: Int)
    implicit def ccToJValue(data: CC)(implicit formats: Formats): JValue = Extraction.decompose(data)

    val json = ("api_key" -> "1234") ~ ("attributes" -> List(CC("123", 123), CC("222", 222)))

    println(write(json))
}