Akka-http:如何将响应映射到对象
Akka-http: How do I map response to object
不确定我是否正确处理了整个路由 DSL 问题,但这就是问题所在。我想对外部服务做一个 post,例如:
val post = pathPrefix("somePath") {
post {
//get the response mapped to my Output object
}
}
然后我希望将响应(Json)映射到与字段匹配的对象,例如输出(假设我已设置 Json 协议)。这是怎么做到的?
我想你想问的是如何将正文以 JSOn 格式获取到你
的案例 class
这是一个简单的例子:
path("createBot" / Segment) { tag: String =>
post {
decodeRequest {
entity(as[CaseClassName]) { caseclassInstance: CaseClassName =>
val updatedAnswer = doSomeStuff(caseclassInstance)
complete {
"Done"
}
}
}
您可以从这里找到更详细的示例:https://github.com/InternityFoundation/Whosebugbots/blob/master/src/main/scala/in/internity/http/RestService.scala#L56
我希望它能回答你的问题。
您正在使用 HTTP 服务器指令来 "retrieve" 某些东西 "externally"。这通常是 HTTP 客户端所做的。
对于这类事情,您可以使用 akka http client api。
例如:
val response = Http().singleRequest(HttpRequest(uri = "http://akka.io"))
response onComplete {
case Success(res) =>
val entity = Unmarshal(res.entity).to[YourDomainObject]
// use entity here
case Failure(ex) => // do something here
}
但是,这需要一些 Unmarshaller (to deserialize the received json). Take also a look at Json Support,因为它可以帮助您轻松定义编组器:
case class YourDomainObject(id: String, name: String)
implicit val YourDomainObjectFormat = jsonFormat2(YourDomainObject)
不确定我是否正确处理了整个路由 DSL 问题,但这就是问题所在。我想对外部服务做一个 post,例如:
val post = pathPrefix("somePath") {
post {
//get the response mapped to my Output object
}
}
然后我希望将响应(Json)映射到与字段匹配的对象,例如输出(假设我已设置 Json 协议)。这是怎么做到的?
我想你想问的是如何将正文以 JSOn 格式获取到你
的案例 class这是一个简单的例子:
path("createBot" / Segment) { tag: String =>
post {
decodeRequest {
entity(as[CaseClassName]) { caseclassInstance: CaseClassName =>
val updatedAnswer = doSomeStuff(caseclassInstance)
complete {
"Done"
}
}
}
您可以从这里找到更详细的示例:https://github.com/InternityFoundation/Whosebugbots/blob/master/src/main/scala/in/internity/http/RestService.scala#L56
我希望它能回答你的问题。
您正在使用 HTTP 服务器指令来 "retrieve" 某些东西 "externally"。这通常是 HTTP 客户端所做的。
对于这类事情,您可以使用 akka http client api。
例如:
val response = Http().singleRequest(HttpRequest(uri = "http://akka.io"))
response onComplete {
case Success(res) =>
val entity = Unmarshal(res.entity).to[YourDomainObject]
// use entity here
case Failure(ex) => // do something here
}
但是,这需要一些 Unmarshaller (to deserialize the received json). Take also a look at Json Support,因为它可以帮助您轻松定义编组器:
case class YourDomainObject(id: String, name: String)
implicit val YourDomainObjectFormat = jsonFormat2(YourDomainObject)