Reputation: 95
im trying to use the Anonymous chat app provided by the Activator for my own purpose .i need to fire a case depending on a json field value. i have a code like this.
def receive = LoggingReceive {
case js: JsValue => {
(js \ "status").validate[String] map {
Utility.escape(_)
}map {
board ! Message(uid, _)
}
i want to match the status field with string values. i tried this approach
(js \ "status").validate[String] map {
Utility.escape(_)
}toString match {
case "play" =>
board ! Message(uid, "play")
case "stop" =>
board ! Message(uid, "stop")
}
but im getting an java.nio.channels.ClosedChannelException im coming from java background and a total newbie to Scala any help would be much appriciated
Upvotes: 0
Views: 1812
Reputation: 8901
You're matching against the result of validate[String]
, which is either JsSuccess
or JsError
, so I would do something like this:
(js \ "status").validate[String] match {
case JsSuccess("play", _) => board ! Message(uid, "play")
case JsSuccess("stop", _) => board ! Message(uid, "stop")
case _ => // something else!
}
If "play" and "stop" are the only values you expecting you could simplify that by binding the command in the extractor directly:
(js \ "status").validate[String] match {
case JsSuccess(cmd, _) => board ! Message(uid, cmd)
}
If you really don't care about the value of status if it doesn't exist or is something else, using asOpt
instead of validate
might be easier:
(js \ "status").asOpt[String].map { cmd =>
board ! Message(uid, cmd)
}
Upvotes: 2