小编Enk*_*obo的帖子

在 akka-http Scala 中将泛型类型注册到 Spray-json-support 的正确方法是什么?

所以,我有这门课:

case class Something[T](data: Option[T] = None)
Run Code Online (Sandbox Code Playgroud)

我按照https://github.com/spray/spray-jsonhttps://doc.akka.io/docs/akka-http/current/common/json-support.html 中的说明注册它。像这样:

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

trait InternalJsonFormat extends SprayJsonSupport with DefaultJsonProtocol {
    import spray.json._

    implicit def somethingFormat[A :JsonFormat] = jsonFormat1(Something.apply[A])
}
Run Code Online (Sandbox Code Playgroud)

最后我complete从 akka http 指令中使用。像这样:

import akka.http.scaladsl.server.Directives._

object ResponseIt extends InternalJsonFormat {
    def apply[T](rawData: T) = {
        val theResponse = Something(data = Some(rawData))
        complete(theResponse)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我在complete(theResponse). 它说

Type mismatch, expected: ToResponseMarshallable, actual: Something[T]
Run Code Online (Sandbox Code Playgroud)

================================================== ==========

我尝试编辑最后的代码以进行调试,如下所示:

object ResponseIt extends InternalJsonFormat {
    import spray.json._ …
Run Code Online (Sandbox Code Playgroud)

generics scala akka spray-json akka-http

3
推荐指数
1
解决办法
394
查看次数

标签 统计

akka ×1

akka-http ×1

generics ×1

scala ×1

spray-json ×1