所以,我有这个类:
case class Something[T](data: Option[T] = None)
我按照中的说明注册https://github.com/spray/spray-json和https://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])
}
最后我使用了akkahttp指令中的complete
。像这样:
import akka.http.scaladsl.server.Directives._
object ResponseIt extends InternalJsonFormat {
def apply[T](rawData: T) = {
val theResponse = Something(data = Some(rawData))
complete(theResponse)
}
}
然后我在complete(theResponse)
中得到一个错误。上面写着
Type mismatch, expected: ToResponseMarshallable, actual: Something[T]
==============================================
出于调试目的,我尝试编辑最后一段代码,如下所示:
object ResponseIt extends InternalJsonFormat {
import spray.json._
def apply[T](rawData: T) = {
val theResponse = Something(data = Some(rawData))
val trying = theResponse.toJson
complete(theResponse)
}
}
并在CCD_ 3中得到新的错误。像这样:
No implicits found for parameter writer: JsonWriter[Something[T]]
所以,我真的很困惑我的代码中出了什么问题?。有什么正确的方法可以在akkahttp中使用spray-json支持吗?
提前感谢
你看,这里没有证据表明你的T
存在JsonFormat
:
def apply[T](rawData: T) = {
// ^--- here
val theResponse = Something(data = Some(rawData))
val trying = theResponse.toJson
complete(theResponse)
}
可以重写此方法以为通用T
:提供JsonFormat
def apply[T](rawData: T)(implicit formatter: JsonFormat[T])