Skip to content

Instantly share code, notes, and snippets.

@derekwyatt
Last active December 16, 2015 02:39
Show Gist options
  • Save derekwyatt/5364264 to your computer and use it in GitHub Desktop.
Save derekwyatt/5364264 to your computer and use it in GitHub Desktop.
Transparent deserialization of a JsValue in pattern matching
import spray.json._
object MyProtocol extends DefaultJsonProtocol {
implicit object MyMessageFormat extends RootJsonFormat[MyMessage] {
def write(msg: MyMessage) = JsObject("arg1" -> JsString(msg.arg1), "arg2" -> JsString(msg.arg2))
def read(value: JsValue) = value.asJsObject.getFields("arg1", "arg2") match {
case Seq(JsString(arg1), JsString(arg2)) => new MyMessage(arg1, arg2)
case _ => deserializationError("MyMessage expected")
}
}
}
case class MyMessage(arg1: String, arg2: String)
object MyMessage {
def unapply(any: Any): Option[(String, String)] = {
if (any.isInstanceOf[MyMessage]) {
val msg = any.asInstanceOf[MyMessage]
Some((msg.arg1, msg.arg2))
} else if (any.isInstanceOf[JsValue]) {
any.asInstanceOf[JsValue].asJsObject.getFields("arg1", "arg2") match {
case Seq(JsString(arg1), JsString(arg2)) =>
Some(arg1, arg2)
case _ => None
}
} else {
None
}
}
}
object ProtocolMixing extends App {
import MyProtocol._
type Receive = PartialFunction[Any, Unit]
def receive: Receive = {
case MyMessage(arg1, arg2) =>
println(s"arg1: $arg1, arg2: $arg2")
}
receive(MyMessage("one", "two"))
receive(MyMessage("one", "two").toJson)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment