我想在scala中使用spray实现一个简单的json REST服务器,它支持以下路由:
GET /foo => return a list of case class objects in json format
POST /bar => read a json into a case class object and perform some computation
我的基本入门代码如下:
import spray.routing.SimpleRoutingApp
import spray.can.Http
import akka.actor.ActorSystem
import akka.actor.Props
import akka.io.IO
import scala.collection.JavaConversions
import com.fasterxml.jackson.databind.ObjectMapper
object SprayTest extends App with SimpleRoutingApp {
implicit val system = ActorSystem("my-system")
val mapper = new ObjectMapper
case class Foo(a: String, b: Int)
case class Bar(c: Long, d: String)
startServer(interface = "localhost", port = 8080) {
get {
path("foo") {
complete {
val c = listOfFoo()
mapper.writeValueAsString(c)
}
}
} ~ post {
path("bar") {
val bar: Bar = ???
complete {
"???"
}
}
}
}
}
我所知道的这段代码的两个最重要的未解决问题是:
有谁知道最好的方法?有没有办法使编码自动,所以我可以执行类似
complete { caseObject }
并拥有 caseObject
自动转换成 json (反之亦然,定义 POST 方法)?
最佳答案
绝对使用喷雾json。通常你将数据模型分离到它们自己的文件中:
import spray.json._
case class Foo(a: String, b: Int)
case class Bar(c: Long, d: String)
object FooBarJsonProtocol extends DefaultJsonProtocol{
implicit val fooFormat = jsonFormat2(Foo)
implicit val barFormat = jsonFormat2(Bar)
}
然后在路线
import FooBarJsonProtocol._
...
get {
path("foo") {
complete {
listOfFoo() //with the implicit in scope this will serialize as json
}
}
} ~ post {
path("bar") {
entity(as[Bar]) { bar => //extract json Bar from post body
complete(bar) //serialize bar to json (or whatever processing you want to do)
}
}
}
}
关于json - 在scala中使用spray编写一个简单的json REST服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24092057/