我有一个 Actor 在 Play 2.3中从websocket接收JsValue。我也有一个定义Reads转换器的case类。当我尝试对案例类进行模式匹配时,它总是针对JsValue而不是案例类进行匹配。

case class Ack(messageType: String, messageId: Int){
  implicit val ackReads: Reads[Ack] = (
      (JsPath \ "message_type").read[String] and
      (JsPath \ "message_id").read[Int]
  )(Ack.apply _)
}


class ChannelActor(out: ActorRef) extends Actor{
  def receive = {
    case a: Ack =>
      println(s"Acknowledged! $a")
    case msg: JsValue =>
      println("Got other jsvalue")
    case _ =>
      println("Got something else")
  }
}

如何将我从WebSocket接收到的JsValue与case类中的Reads验证器进行模式匹配?

编辑:我找到了一种解决方法,可以通过手动对JsValue进行模式匹配来找出我随后需要验证的类型。现在的代码如下所示:
case class Ack(messageType: String, messageId: Int)
object Ack{
  implicit val ackReads: Reads[Ack] = (
    (JsPath \ "message_type").read[String](verifying[String](_ == "ack")) and
    (JsPath \ "message_id").read[Int]
  )(Ack.apply _)

  implicit val ackWrites: Writes[Ack] = (
      (JsPath \ "message_type").write[String] and
      (JsPath \ "message_id").write[Int]
  )(unlift(Ack.unapply))
}


class ChannelActor(out: ActorRef) extends Actor{
  def receive = {
    case msg: JsValue =>
      (msg \ "message_type").asOpt[String] match {
        case Some("ack") =>
          msg.validate[Ack] match{
            case ack: JsSuccess[Ack] => println("got valid ack message")
            case e: JsError => out ! Json.obj("error" -> s"invalid format for ack message ${JsError.toFlatJson(e).toString()}")
          }
        case None => out ! Json.obj("error" -> "you must send a message_type with your json object")
        case t => out ! Json.obj("error" -> s"unknown message type ${t.get}")
      }
    case _ => out ! Json.obj("error" -> "unknown message format")
  }
}

这样可以达到我想要的目的,但是我感觉这不是在Play中验证JSON消息的“正确”或最优雅的解决方案,并且随着我实现更多消息类型而变得困惑。

最佳答案

http://www.playframework.com/documentation/2.3.x/ScalaWebSockets

它在逐字记录的文档中

import play.api.libs.json._

implicit val inEventFormat = Json.format[InEvent]
implicit val outEventFormat = Json.format[OutEvent]

import play.api.mvc.WebSocket.FrameFormatter

implicit val inEventFrameFormatter = FrameFormatter.jsonFrame[InEvent]
implicit val outEventFrameFormatter = FrameFormatter.jsonFrame[OutEvent]

import play.api.mvc._
import play.api.Play.current

def socket = WebSocket.acceptWithActor[InEvent, OutEvent] { request => out =>
  MyWebSocketActor.props(out)
}

编辑:确定了。问题是Json.format写入方法不提供有关类型的信息。让我更深入地看看。

例如
case class Test(a: String)
implicit val f = Json.format[Test]
f.writes(Test1("hey")) // >> {"a":"hey"} note nothing says it's a Test1 instances

09-25 21:40