HTTP 请求的主体作为 spray-json 对象

Body of HTTP-request as spray-json object

我想用 spray 创建一个简单的休息服务。其余服务应通过 http put 接收 json-body。我想将解析后的 json-string 传递给函数进行进一步处理。

是否有任何示例可以做到这一点?我还没有找到任何示例如何将 http put 请求的主体作为已解析的 json 对象访问 (spray-json)?

谢谢。

这里是示例代码,供您参考。

import spray.http._
import spray.routing._

import spray.json.DefaultJsonProtocol
import spray.httpx.unmarshalling._
import spray.httpx.marshalling._

case class Person(fname: String, lname: String, age: Int)

object MyJsonProtocol extends DefaultJsonProtocol {
  implicit val PersonFormat = jsonFormat3(Person)
}

class TestActor extends HttpServiceActor {
  import MyJsonProtocol._
  import spray.httpx.SprayJsonSupport._

  override def receive: Receive = runRoute(serviceRoute)

  private val serviceRoute = path("test_end_point") {
    put {
      entity(as[Person]) { person =>
        println(person)
        complete(StatusCodes.OK)
      }
    }
  }

}

我使用以下命令对其进行了测试

curl -X PUT  -H "Content-Type: application/json" --data '{ "fname": "Vishal", "lname" :"John", "age" : 32 }' localhost:9000/test_end_point