Last active
December 16, 2015 02:39
-
-
Save derekwyatt/5364264 to your computer and use it in GitHub Desktop.
Transparent deserialization of a JsValue in pattern matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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