我在尝试为我的案例类编写jsonProtocol时注意到我在嵌套案例类中遇到错误。然而,如果我将案例类解耦并只创建一个包含所有字段的大型案例类,它将正常工作。
case class Invited(invited:Array[Int])
case class Event(eventName:String,eventID:Int,invited: Invited)
object jsonProtocol extends DefaultJsonProtocol {
implicit val invitedFormat = jsonFormat(Invited,"people Invited")
implicit val eventFormat = jsonFormat3(Event)
}
object WebServer {
def main(args:Array[String]): Unit ={
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
implicit val dispatcher = system.dispatcher
//println(Event("HelloEvent",2,Array(1,2,3)).toString)
val route = {
import jsonProtocol._
path("Event") {
post{
entity(as[Event]) {event =>
println(event.eventName)
complete(event)
}
}
}
}
val bindingFuture = Http().bindAndHandle(route,"localhost",8080)
StdIn.readLine() // let it run until user presses return
bindingFuture
.flatMap(_.unbind()) // trigger unbinding from the port
.onComplete(_ => system.terminate()) // and shutdown when done
}
}
complete(event)
行给我一个错误,说明预期ToResponseMarshallable
,实际事件。
答案 0 :(得分:3)
要在使用带有akka http的spray json时修复编组错误,您需要将SprayJsonSupport
混合到jsonProtocol
对象中。
所以只需添加导入:
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
并更改行:
object jsonProtocol extends DefaultJsonProtocol {
为:
object jsonProtocol extends DefaultJsonProtocol with SprayJsonSupport {
PS根据scalastyle,您应该使用^[A-Z][A-Za-z]*
命名对象,因此jsonProtocol
中的第一个字母应为大写