使用Scala Play

时间:2016-12-06 21:20:31

标签: json scala playframework

我想要返回呈现为Json的两个不同对象。我已经写了他们的隐式写入,我想以连锁的方式回复它们。

无论我做什么,我都会收到错误Compilation error[No Json serializer found for type Seq[models.RedisInfo]. Try to implement an implicit Writes or Format for this type

这是我的代码如何进行

def listAll() = Action.async { implicit request =>
  import models.Psql.{sqlUploadWrites => sqlWrites}
  import models.Redis.{redisWrites}

  val rFut:Future[Seq[RedisInfo]] = Redis.listAll()
  val sqlFut:Future[Seq[SQLInfo]] = SQL.listAll()
  val resp = Future.sequence(Seq(rFut, sqlFut)).map{

    /* Now I want to use their individual write methods to create the Json    
    and then wrap the result of the two into a Future[Result]

    case x: Seq[RedisInfo] => x.map(res => Json.toJson(res)(redisWrites))
    case y: Seq[SQLInfo] => y.map(res => Json.toJson(res)(sqlWrites))


  }

序列的长度不一样。当我单独进行时,这似乎也有效。所以我想知道在这种情况下存在多大的复杂性。

1 个答案:

答案 0 :(得分:0)

由于您尚未提供redisWrites的写入实现,因此无法对此进行评论。

我实现类似的方法首先是实现Format的读写方法,然后为此创建隐式。

Object Formatter {
    def uuidFormat: Format[UUID] = new Format[UUID] {
    def writes(uuid: UUID): JsString = JsString(uuid.toString)
    def reads(value: JsValue): JsResult[UUID] = value match {
      case JsString(x) => UUID.fromString(x) match {
        case Success(uuid) => JsSuccess(uuid)
        case Failure(msg) => JsError(__ \ 'UUID, ValidationError("invalid UUID", msg))
      }
      case _ => JsError(__ \ 'UUID, ValidationError("invalid UUID", "Missing UUID String"))
    }
  }
  implicit val uuidFormat = uuidFormat
}

然后导入uuidFormat,无论你需要执行json serde

import Formatter.uuidFormat