好的,这真是让我烦恼。我已经使用spray和scala,akka实现了一个REST api。我已经成功实现了spall get,post路由来查询mysql数据库并给出了json输出。我能够在post体内发送参数,但是我无法发送与JSON相同的参数。它看起来很简单但它只是不工作。我收到错误 - 来自服务器的空回复。请帮忙。
这是我的示例curl命令:
curl -H "Content-Type: application/json" -X POST -d '{ "name": "Jane", "favNumber" : 42 }' http://localhost:8080/jsonTesting
我正在尝试这个小样本代码,看看是否可以解组json参数并获得所需的输出。如果它工作,那么我在我的实际代码中实现相同的。
import spray.json.DefaultJsonProtocol
import spray.json._
import spray.httpx.SprayJsonSupport
object MyJsonProtocol extends DefaultJsonProtocol with SprayJsonSupport {
implicit val Format = jsonFormat2(Person)
case class Person(name:String, favNumber:Int)
//Spray main class
import akka.actor.ActorSystem
import spray.routing.SimpleRoutingApp
import spray.json.DefaultJsonProtocol
import spray.json._
import spray.http.MediaTypes._
import MyJsonProtocol._
import spray.routing._
object SprayTest extends App with SimpleRoutingApp {
implicit val system = ActorSystem()
def testRoute(route: Route): Route = {
post {
respondWithMediaType(`application/json`){
route
}
}
}
startServer(interface = "localhost", port = 8080) {
testRoute {
path("departed") {
parameter('count.as[Boolean]) {count =>
complete(if (count == true) "even ball" else "odd ball")
}
}
} ~
path("jsonTesting") {
post{
entity(as[Person]) { person =>
complete(s"Person: ${person.name} - favoritenumber:${person.favNumber}")
}
}
}
}
}
这是错误:
Uncaught error from thread [default-akka.actor.default-dispatcher-2] shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for ActorSystem[default]
java.lang.NoSuchMethodError: spray.json.JsonParser$.apply(Ljava/lang/String;)Lspray/json/JsValue;
at spray.httpx.SprayJsonSupport$$anonfun$sprayJsonUnmarshaller$1.applyOrElse(SprayJsonSupport.scala:36)
at spray.httpx.SprayJsonSupport$$anonfun$sprayJsonUnmarshaller$1.applyOrElse(SprayJsonSupport.scala:34)
at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36)
at spray.httpx.unmarshalling.Unmarshaller$$anon$1$$anonfun$unmarshal$1.apply(Unmarshaller.scala:29)
at spray.httpx.unmarshalling.SimpleUnmarshaller.protect(SimpleUnmarshaller.scala:40)
at spray.httpx.unmarshalling.Unmarshaller$$anon$1.unmarshal(Unmarshaller.scala:29)
at spray.httpx.unmarshalling.SimpleUnmarshaller.apply(SimpleUnmarshaller.scala:29)
at spray.httpx.unmarshalling.SimpleUnmarshaller.apply(SimpleUnmarshaller.scala:23)
at spray.httpx.unmarshalling.UnmarshallerLifting$$anon$3.apply(UnmarshallerLifting.scala:35)
Sbt dependecies:
libraryDependencies ++= Seq(
"com.typesafe.akka" %% "akka-actor" % "2.3.6",
"com.typesafe.akka" %% "akka-http-experimental" % "0.7",
"io.spray" %% "spray-json" % "1.3.2",
"io.spray" %% "spray-routing" % sprayVersion,
"io.spray" %% "spray-client" % sprayVersion,
"io.spray" %% "spray-testkit" % sprayVersion % "test",
"mysql" % "mysql-connector-java" % "5.1.25",
"com.typesafe.slick" %% "slick" % "3.0.0",
"com.typesafe.scala-logging" %% "scala-logging-slf4j" % "2.1.2"
)