如何在AKKA-HTTP

时间:2016-03-02 21:16:16

标签: json scala http akka akka-http

我是acala和akka的新手,所以问题可能有些愚蠢。

我有一个班级:

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")

}

但错误说:

  

错误:(39,20)类型不匹配;发现:   scala.concurrent.Future [选项[com.cassandra.phantom.modeling.MiTabla.User]]   必需:akka.http.scaladsl.marshalling.ToResponseMarshallable               getById(ID)

返回Fson的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)
}

2 个答案:

答案 0 :(得分:0)

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

的内容,则会有效
val route = pathSingleSlash {
    get { ctx =>
      ctx.complete(getById())
    }
}

答案 1 :(得分:0)

查看: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)
}