Reputation: 3
I've noticed while trying to write a jsonProtocol for my case classes that I get errors with nested case classes. Whereas, if I decouple the case classes and just create one giant case class, with all the fields, it will work fine.
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
}
}
The line with complete(event)
gives me a an error saying expected ToResponseMarshallable
, actual event.
Upvotes: 0
Views: 88
Reputation: 998
To fix the marshalling error while using spray json with akka http, you need to mix the SprayJsonSupport
into your jsonProtocol
object.
So simply add import:
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
and change line:
object jsonProtocol extends DefaultJsonProtocol {
to:
object jsonProtocol extends DefaultJsonProtocol with SprayJsonSupport {
PS according to scalastyle, you should name objects with ^[A-Z][A-Za-z]*
, so the First letter should be uppercase in jsonProtocol
Upvotes: 3