【问题标题】:Convert Future result into json将 Future 结果转换为 json
【发布时间】:2023-03-25 21:18:01
【问题描述】:

我有两种沟通模式:

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 中保存类型以供将来使用的最佳方法是什么?

【问题讨论】:

    标签: scala akka


    【解决方案1】:

    您的OkResponse 中的model 值的类型未知,因此您得到底部类型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)) 
    }
    

    【讨论】:

    • 是的,这符合预期,但我有很多模型,是否可以不匹配所有模型?
    • 您需要模型的类型来获取该模型的 Json 类型类,它将您的模型格式化为 json。也许您可以在您的问题中为我们提供更多背景信息。现在看起来您想将消息 id(一个 Int)转换为 json,而与模型类型无关。
    • 这是整个问题:)。我可能会创建一些像MainObject 这样的东西,然后用它扩展PostTag,并为ADT 创建json writer,但也许可以通过TypeTag 自动传递。
    • @mike 为每种模型类型创建一个MyActorService 可能更容易,而不是使用一个MyActorService 来返回每种模型类型。然后你就会知道你会收到哪种类型的模型。
    • @mike 您可以在myFormats 中为您的消息进行模式匹配,将消息作为输入参数并将适当的Json.format 显式传递给Json.toJson。那时一切都将集中在一个地方
    猜你喜欢
    • 2021-12-28
    • 2018-10-25
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    相关资源
    最近更新 更多