Skip to content

Instantly share code, notes, and snippets.

@arussel
Created November 21, 2013 10:37
Show Gist options
  • Save arussel/7579463 to your computer and use it in GitHub Desktop.
Save arussel/7579463 to your computer and use it in GitHub Desktop.
object Test {
case class A(name: String, value: String = "value")
case class B(name: String, value: String = "value")
case class C(name: String, value: String = "value")
implicit val fullAFormater: OFormat[(A, Seq[(B, Seq[C])])] = ((JsPath \ "name").format[String]
and (JsPath \ "value").format[String]
and (JsPath \ "bs").format[Seq[(B, Seq[C])]])({
(name: String, value: String, bs: Seq[(B, Seq[C])]) => (A(name, value), bs)
}, {
t: (A, Seq[(B, Seq[C])]) => (t._1.name, t._1.value, t._2)
})
implicit val fullBFormatter: OFormat[(B, Seq[C])] = ((JsPath \ "name").format[String]
and (JsPath \ "value").format[String]
and (JsPath \ "cs").format[Seq[C]])({
(name: String, value: String, cs: Seq[C]) => (B(name, value), cs)
}, {
t => (t._1.name, t._1.value, t._2)
})
implicit val cFormatter = format[C]
def test {
val obj = (A("a"), Seq((B("b1"), Seq(C("c11"), C("c12"))), (B("b2"), Seq(C("c21"), C("c22")))))
val json = Json.toJson(obj)
println(json)
}
}
@mandubian
Copy link

It's due to order of implicits... fullAFormater requires an implicit Format[C] but it's declared afterwards which is not good.
The compiler can compile it for an unknown reason but then you get a weird NPE.

here is the code a bit refactored!

object Test {

  case class A(name: String, value: String = "value")
  case class B(name: String, value: String = "value")
  case class C(name: String, value: String = "value")

  implicit val cFormatter = Json.format[C]

  implicit val fullBFormatter: Format[(B, Seq[C])] = (
     (JsPath \ "name").format[String] and
     (JsPath \ "value").format[String] and
     (JsPath \ "cs").format[Seq[C]]
  )(
   { (name: String, value: String, cs: Seq[C]) => (B(name, value), cs) },
   { t => (t._1.name, t._1.value, t._2) }
  )

  implicit val fullAFormater: Format[(A, Seq[(B, Seq[C])])] = (
    (JsPath \ "name").format[String] and
    (JsPath \ "value").format[String] and
    (JsPath \ "bs").format[Seq[(B, Seq[C])]]
  )(
    { (name: String, value: String, bs: Seq[(B, Seq[C])]) => (A(name, value), bs) },
    { t: (A, Seq[(B, Seq[C])]) => (t._1.name, t._1.value, t._2) }
  )

  def test() = {
    val obj = (A("a"), Seq((B("b1"), Seq(C("c11"), C("c12"))), (B("b2"), Seq(C("c21"), C("c22")))))
    val json = Json.toJson(obj)
    println(json)
  }
}

BTW OFormat is quite technical, just use Format if you don't need OFormat explicitly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment