Skip to content

Instantly share code, notes, and snippets.

@nachinius
Created August 25, 2017 12:38
Show Gist options
  • Save nachinius/c7520fda45c435acc97243a8e6ca1a8e to your computer and use it in GitHub Desktop.
Save nachinius/c7520fda45c435acc97243a8e6ca1a8e to your computer and use it in GitHub Desktop.
Usage of spray json in Scala hierarchy of classes
import spray.json.JsonParser
val msg =
"""
| {"action":"move","data":{"direction":"left"}}
""".stripMargin
JsonParser(msg).asJsObject.getFields("action","data")(1).asJsObject.getFields("direction")
case class B(val afieldOfb: String)
case class A(val afieldOfa: String, val bFieldOfA: B)
val a = A("hola",B("soy b"))
import spray.json._
import DefaultJsonProtocol._
implicit val aFormat: RootJsonFormat[A] = jsonFormat2(A)
implicit val bFormat: RootJsonFormat[B] = jsonFormat1(B)
val b = a.toJson
b.convertTo[A]
//====== with traits and hierarchy of class
// a hierarchy of case classes
class C()
case class E(efield: String) extends C
case class F(ffield: String, f2field: String) extends C
// one that contains
case class Container(c: C)
val a1 = Container(E("evalue"))
val a2 = Container(F("fvalue","fvalue2"))
//implicit val containerFormat: RootJsonFormat[Container] = jsonFormat1(Container)
implicit val eFormat = jsonFormat1(E)
implicit val fFormat = jsonFormat2(F)
object MyJsonProtocol extends DefaultJsonProtocol {
implicit object ContainerJsonFormat extends RootJsonFormat[Container] {
override def write(obj: Container) = {
obj match {
case Container(x: E) => JsObject(
"type" -> JsString("E"),
"data" -> x.toJson
)
case Container(x: F) => JsObject(
"type" -> JsString("F"),
"data" -> x.toJson
)
case _ => JsObject(
"type" -> JsString("X"),
"data" -> JsString("")
)
}
}
override def read(json: JsValue) = {
json.asJsObject.getFields("type","data") match {
case Seq(JsString("E"),x) => Container( x.convertTo[E])
case Seq(JsString("F"),x) => Container( x.convertTo[F])
}
}
}
}
import MyJsonProtocol._
a1
a2
val a1j = a1.toJson
val a2j = a2.toJson
a1j.convertTo[Container]
a2j.convertTo[Container]
val msg2 =
"""
| {"type":"E","data":{"efield":"left","extra":"willnotapper"}}
""".stripMargin
JsonParser(msg2).convertTo[Container]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment