1
我對這兩種模式進行通信:轉換未來的結果爲JSON
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
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中爲將來的工作保存類型的最佳方法是什麼?
是的,這項工作如預期,但我有很多模型,是否有可能沒有匹配所有模型? – mike
您需要獲取該模型的'Json'類類的模型類型,該類將您的模型格式化爲json。也許你可以在你的問題中給我們更多的背景。現在看起來你想把一個消息id(一個Int)變成json,而不管模型的類型如何。 –
這是整個問題:)。我可能會創建一些類似於'MainObject'的文件,然後擴展'Post'和'Tag',併爲ADT創建json writer,但也可能會自動通過TypeTag傳遞。 – mike