2017-03-08 106 views
0

我正在創建一個期望Json的Finch端點。如何將請求參數指定爲Json類型

URL - LogBundles /龍JSON消息/過程

我使用json4s庫JSON解析

如何指定身體類型JSON或如何傳遞LogBundles和過程之間的一個JSON值?

我不能做body.as [case class],因爲我不會知道Json的確切結構。 我只會在解析時尋找特定的鍵。

代碼

val bundleProcessEndpoint: Endpoint[String] = put("LogBundles" :: body :: "Process") { id => 
       val jsonBody = parse(id)} 

ERROR

找不到參數d隱含值:io.finch.Decode.Aux [A,CT] [錯誤] VAL bundleProcessEndpoint:端點[String] = put(「LogBundles」:: body ::「Process」){id:JsonInput =>

回答

1

有幾種方法可以做到這一點,儘管它們都沒有被視爲我對芬奇來說是一個原因。接受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)) 
+0

你好弗拉基米爾,糾正我,如果我錯了。但我的問題是如何從端點消耗用戶發送的PUT請求的Json負載。 WithBody覆蓋用戶發送的有效負載。 –

+0

這兩個示例中的最後一行僅僅是爲了演示端點在給定輸入上返回的內容。你不需要它在你的應用程序中。我鼓勵你看看我們的[用戶指南](https://finagle.github.io/finch/user-guide.html),它可以幫助你清除所有的困惑。 –