0

我有一个烧瓶应用程序,如果我对其执行 cURL,它会返回以下内容:

响应采用JSON 格式,如下所示:

{"your_field": "hello there buddy"}

我只想得到值“你好,哥们”并打印出来。知道怎么做吗?

我有以下代码:

def myExampleFunction  = ( text: String ) => {

  val result = Http("http://localhost:5001/other/post").postData("{\"my_field\":\"" + text + "\"}")
    .header("Content-Type", "application/json")
    .header("Charset", "UTF-8")
    .option(HttpOptions.readTimeout(10000)).asString

  println("result.body is!! : " + result.body)
  result.body

运行此打印以下内容:

result.body is!! : {"your_field": "hello there buddy"}

我想要实现的是:

result.body is!! : hello there buddy

4

1 回答 1

1

result.body类型为string,将字符串数据解析为 json 数据,提取出必填字段。

在下面的代码中,我使用json4s库来解析对 json 数据的字符串响应。

  def myExampleFunction  = ( text: String ) => {
    import org.json4s._
    import org.json4s.native.JsonMethods._
    implicit val formats = DefaultFormats

    val result = Http("http://localhost:5001/other/post")
      .postData("{\"my_field\":\"" + text + "\"}")
      .header("Content-Type", "application/json")
      .header("Charset", "UTF-8")
      .option(HttpOptions.readTimeout(10000))
      .asString

    (parse(result.body) \\ "your_field").extract[String]
}

于 2020-05-13T04:37:35.737 回答