Enk*_*obo 3 generics scala akka spray-json akka-http
所以,我有这门课:
case class Something[T](data: Option[T] = None)
Run Code Online (Sandbox Code Playgroud)
我按照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])
}
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._
def apply[T](rawData: T) = {
val theResponse = Something(data = Some(rawData))
val trying = theResponse.toJson
complete(theResponse)
}
}
Run Code Online (Sandbox Code Playgroud)
并在val trying = theResponse.toJson. 像这样:
No implicits found for parameter writer: JsonWriter[Something[T]]
Run Code Online (Sandbox Code Playgroud)
所以,我真的很困惑我的代码有什么问题?有没有正确的方法可以在 akka http 中使用喷雾 json 支持?
提前致谢
你看,没有证据证明JsonFormat你T在这里的存在:
def apply[T](rawData: T) = {
// ^--- here
val theResponse = Something(data = Some(rawData))
val trying = theResponse.toJson
complete(theResponse)
}
Run Code Online (Sandbox Code Playgroud)
可以重写此方法以提供JsonFormatgeneric T:
def apply[T](rawData: T)(implicit formatter: JsonFormat[T])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
394 次 |
| 最近记录: |