如何在 AKKA-HTTP 中编组 Future[Option[Foo]] class 到 JSON

How to Marshall a Future[Option[Foo]] class to JSON in AKKA-HTTP

我是 acala 和 akka 的新手,所以这个问题可能有点傻。

我有一个 class:

case class Foo(colUNO: String, colDOS: Long)

我有一个功能:

getById() : Future[Option[Foo]]

我正在尝试在 akka-http 路由中使用它

def main(args: Array[String]) {

implicit val actorSystem = ActorSystem("system")
implicit val actorMaterializer = ActorMaterializer()

val route = pathSingleSlash {

    get {

      complete {

        val fut = getById()

        }
    }
}

Http().bindAndHandle(route,"localhost",8080)
println("server started at 8080")

}

但错误显示:

Error:(39, 20) type mismatch; found : scala.concurrent.Future[Option[com.cassandra.phantom.modeling.MiTabla.User]] required: akka.http.scaladsl.marshalling.ToResponseMarshallable getById(id)

我必须对 return Foo 的 Json 做什么?

谢谢!!


决议:

正在看:http://doc.akka.io/docs/akka-stream-and-http-experimental/2.0.3/scala/http/common/json-support.html 并添加以下代码:

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json._

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val userFormat = jsonFormat2(Foo)
}

这将解决您的 Future 问题。如果你有将 Option[com.cassandra.phantom.modeling.MiTabla.User]] 转换为 ToResponseMarshallable

的东西,并且会起作用
val route = pathSingleSlash {
    get { ctx =>
      ctx.complete(getById())
    }
}

查看:http://doc.akka.io/docs/akka-stream-and-http-experimental/2.0.3/scala/http/common/json-support.html 并添加以下代码:

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import spray.json._

trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  implicit val userFormat = jsonFormat2(Foo)
}