有幾種方法可以做到這一點,儘管它們都沒有被視爲我對芬奇來說是一個原因。接受Endpoint
中的任意JSON對象的安全性更高或更低的方法是下載到通過您正在使用的JSON庫公開的JSON AST API。對於json4s,它將是org.json4s.JsonAST.JValue
。
scala> import io.finch._, io.finch.json4s._, org.json4s._
scala> implicit val formats: Formats = DefaultFormats
formats: org.json4s.Formats = [email protected]
scala> val e = jsonBody[JsonAST.JValue]
e: io.finch.Endpoint[org.json4s.JsonAST.JValue] = body
scala> e(Input.post("/").withBody[Application.Json](Map("foo" -> 1, "bar" -> "baz"))).awaitValueUnsafe()
res2: Option[org.json4s.JsonAST.JValue] = Some(JObject(List((foo,JInt(1)), (bar,JString(baz)))))
這會給你一個JsonAST.JValue
實例你需要手動操作(我假設有暴露的是模式匹配API)。
一個替代方案(和更危險的方法)是要求Finch/JSON4S解碼一個JSON對象爲Map[String, Any]
。但是,只有當您不希望客戶端將JSON數組作爲頂級實體發送時,這才起作用。
scala> import io.finch._, io.finch.json4s._, org.json4s._
scala> implicit val formats: Formats = DefaultFormats
formats: org.json4s.Formats = [email protected]
scala> val b = jsonBody[Map[String, Any]]
b: io.finch.Endpoint[Map[String,Any]] = body
scala> b(Input.post("/").withBody[Application.Json](Map("foo" -> 1, "bar" -> "baz"))).awaitValueUnsafe()
res1: Option[Map[String,Any]] = Some(Map(foo -> 1, bar -> baz))
你好弗拉基米爾,糾正我,如果我錯了。但我的問題是如何從端點消耗用戶發送的PUT請求的Json負載。 WithBody覆蓋用戶發送的有效負載。 –
這兩個示例中的最後一行僅僅是爲了演示端點在給定輸入上返回的內容。你不需要它在你的應用程序中。我鼓勵你看看我們的[用戶指南](https://finagle.github.io/finch/user-guide.html),它可以幫助你清除所有的困惑。 –