将Future结果转换为json

时间:2015-06-20 10:08:48

标签: scala akka

我有两种沟通模式:

case class Post(id: Int, name: String, text: String)
case class Tag(id: Int, name: String)

我为这个模型创建了json格式:

import play.api.libs.json._
object myFormats {
  implicit val postFormat = Json.format[Post]
  implicit val tagFormat = Json.format[Tag]
}        

然后我创建了可以返回OkResponse或BadResponse

的服务(actor)
sealed trait Response
case class OkResponse[T](model: T) extends Response
case class BadResponse(msg: String) extends Response


// easy example  
case class Message(id: Int)

class MyActorService extends Actor {

     def receive = {
        case Message(id) => 
          if (id == 0) {
             sender ! OkResponse(Post(1, "foo", "bar"))
          }  else if (id == 1) {
             sender ! OkResponse(Tag(1, "tag"))
          } else {
             sender ! BadResponse("id overflow")
          }
     }
}

然后我想将模型OkResponse转换为Json值:

(myActorService ? Message(1)).mapTo[Response].map {
  case BadResponse(msg) => println(msg)

  case OkResponse(model) => 
    println(Json.toJson(model)) 
}       

但这不是因为No Json serializer found for type Any. Try to implement an implicit Writes or Format for this type.

而编译的

如何谈论我的模型类型的scala?在scala中保存未来工作类型的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

modelOkResponse值的类型未知,因此您获得底部类型Any

您可以在OkResponse的模型上进行模式匹配。

(myActorService ? Message(1)).mapTo[Response].map {
  case BadResponse(msg) => println(msg)

  case OkResponse(post: Post) => 
    println(Json.toJson(post))

  case OkResponse(tag: Tag) => 
    println(Json.toJson(tag)) 
}