gpt4 book ai didi

json - 在scala中使用spray编写一个简单的json REST服务器

转载 作者:行者123 更新时间:2023-12-03 11:54:03 24 4
gpt4 key购买 nike

我想在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 {
"???"
}
}
}
}
}

我所知道的这段代码的两个最重要的未解决问题是:
  • 我依赖于 jackson ,但从网上搜索来看,spray 似乎应该具有某种内置支持,以支持序列化和反序列化简单的案例对象或案例对象列表。
  • 我不确定从发布请求中获取内容并将其编码为 json 的“最佳”、最惯用和最简洁的方法,以便我可以对案例类对象执行一些计算

  • 有谁知道最好的方法?有没有办法使编码自动,所以我可以执行类似 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com