2017-03-08 7 views
0

Json이 필요한 Finch 엔드 포인트를 작성 중입니다.Json 유형으로 요청 매개 변수를 지정하는 방법

URL -

내가 형 JSON으로 몸을 지정하려면 어떻게

또는 어떻게 할 내가 LogBundles 및 프로세스 사이의 JSON 값을 전달 구문 분석 JSON에 대한 LogBundles/긴 JSON 메시지/프로세스

내가 json4s 사용하고 라이브러리 ?

Json의 정확한 구조를 알지 못해서 body.as [case class]를 수행 할 수 없습니다. 구문 분석하는 동안 특정 키를 찾아 보겠습니다.

코드

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

ERROR

변수 D에 대한 암시 값 찾을 수 없습니다 io.finch.Decode.Aux [A, CT] [오류] 발을 bundleProcessEndpoint : 끝점 [String] = put ("LogBundles":: body :: "Process") {id : JsonInput =>

답변

1

이렇게하는 방법은 여러 가지가 있습니다. 핀치를위한 diomatic. 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에 Map[String, Any]으로 JSON 객체를 디코딩하도록 요청하는 대안이 있습니다. 그러나 이것은 클라이언트가 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)를 살펴 보시기 바랍니다. –