在scala中使用喷雾编写一个简单的json REST服务器
发布时间:2020-12-16 09:42:37 所属栏目:安全 来源:网络整理
导读:我想在scala中实现一个简单的json REST服务器,它支持以下路由: GET /foo = return a list of case class objects in json formatPOST /bar = read a json into a case class object and perform some computation 我的基本入门代码如下: import spray.rou
我想在scala中实现一个简单的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 { "???" } } } } } 我知道的这个代码的两个最重要的开放性问题是: >我依赖于杰克逊,但是从搜索网络,似乎喷雾应该有一些内置的支持序列化和反序列化简单的案例对象或案例对象列表。 有没有人知道最好的方法?有没有办法使编组自动化,所以我可以执行类似于完整的{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) } } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |