4

我使用 PlayFramework 的 Play WS API 与外部 API 进行通信。我需要处理接收到的数据,但不知道如何处理。我得到一个响应,我想将它传递给其他函数,如 JSON 对象。我怎样才能做到这一点?我使用的代码可以在下面看到。谢谢!

def getTasks = Action {
    Async {
      val promise = WS.url(getAppProperty("helpdesk.host")).withHeaders(
        "Accept" -> "application/json",
        "Authorization" -> "Basic bi5sdWJ5YW5vdjoyMDEzMDcwNDE0NDc=" ).get()
      for {
        response <- promise
      } yield Ok((response.json \\ "Tasks"))
    }
  }
4

2 回答 2

1

I get a response, and I want to pass it to other function like an JSON Object.

I'm not sure I understand your question, but I'm guessing you want to transform the json you receive from the WS call prior to returning to the client, and that this transformation could take several lines of code. If this is correct, then you just need to add curly brackets around your yield statement so you can do more work on the response:

def getTasks = Action {
  Async {
    val promise = WS.url(getAppProperty("helpdesk.host")).withHeaders(
      "Accept" -> "application/json",
      "Authorization" -> "Basic bi5sdWJ5YW5vdjoyMDEzMDcwNDE0NDc=" ).get()
    for {
      response <- promise
    } yield {
      // here you can have as many lines of code as you want,
      // only the result of the last line is yielded
      val transformed = someTransformation(response.json)
      Ok(transformed)
    }  
  }
}
于 2013-07-10T19:06:40.233 回答
0

我看了看文档,你可以试试:

Async {
    WS.url(getAppProperty("helpdesk.host")).withHeaders(
        "Accept" -> "application/json",
        "Authorization" -> "Basic bi5sdWJ5YW5vdjoyMDEzMDcwNDE0NDc=" ).get().map{
        response => Ok(response.json \\ "Tasks")
    }      
}
于 2013-07-09T14:26:52.120 回答