8

HttpServiceはjsonを受け取り、それをjson4sライブラリでケースクラスに解析することを定義しようとしています:

import org.http4s._
import org.http4s.dsl._
import org.json4s._
import org.json4s.native.JsonMethods._

case class Request(firstName: String, secondName: String)

HttpService {
  case req @ POST -> Root =>
    val request = parse(<map req.body or req.bodyAsText to JsonInput>).extract[Request]
    Ok()
}

org.json4s.JsonInputまたはからどのように取得できますreq.bodyreq.bodyAsText?

私はまた、 with を使用するために継承することを知っているjson4sので、toまたはStringInputtoに変換する必要があると思いますが、まだ方法がわかりません。StreamInputJsonInputStringInputStreamreq.bodyInputStreamreq.bodyAsTextString

私は Scala を初めて使用し、 などのいくつかの概念をまだ完全には理解していませんscalaz.stream.Process

4

3 に答える 3

6

ピーターの解決策は質問を修正し、それに答えますが、私はここでOPの述べたが意図されていない質問の解決策を探してつまずきました:「リクエストボディを[...] InputStreamとして取得する方法」http4s. GitHub のIssue 634での議論のおかげで、私が思いついたのは次のとおりです。

import java.io.InputStream
import org.http4s._
implicit val inputStreamDecoder: EntityDecoder[InputStream] = 
    EntityDecoder.decodeBy(MediaRange.`*/*`) { msg =>
  DecodeResult.success(scalaz.stream.io.toInputStream(msg.body))
}

そして、HttpService で、そのデコーダーを次のように使用します。

request.as[InputStream].flatMap { inputStream => ...inputStream is an InputStream... }

または、必要に応じて、デコーダーのダンス全体をスキップします。

val inputStream = scalaz.stream.io.toInputStream(request.body)
于 2016-10-02T00:08:19.153 に答える
5

http4s-json4s-jackson(またはhttp4s-json4s-native) パッケージを使用し、を使用して、リクエストから (ケース クラスの名前を以下に変更org.http4s.EntityDecoderしました) を簡単に取得できます。FooRequestFoo

EntityDecoderリクエストボディからエンティティをデコードできる型クラスです。を JSON で取得したいので、JSONをデコードできるFooを作成する必要があります。EntityDecoder[Foo]json4s を使用してこのデコーダーを作成する場合は、Reader(またはJsonFormat) が必要です。

EntityDecoder[Foo]インスタンスがある場合Fooは、リクエストからを取得できますreq.as[Foo]

import org.json4s._
import org.json4s.jackson.JsonMethods._

import org.http4s._
import org.http4s.dsl._
import org.http4s.json4s.jackson._

case class Foo(firstName: String, secondName: String)

// create a json4s Reader[Foo]
implicit val formats = DefaultFormats
implicit val fooReader = new Reader[Foo] { 
  def read(value: JValue): Foo = value.extract[Foo] 
}
// create a http4s EntityDecoder[Foo] (which uses the Reader)
implicit val fooDec = jsonOf[Foo]

val service = HttpService {
  case req @ POST -> Root => 
    // req.as[Foo] gives us a Task[Foo]
    // and since Ok(...) gives a Task[Response] we need to use flatMap
    req.as[Foo] flatMap ( foo => Ok(foo.firstName + " " + foo.secondName) )
}

注: http4s で最も頻繁に使用される json ライブラリ ライブラリは、おそらくArrenautcirceです。そのため、これらのライブラリの 1 つを使用した http4s の例がさらに見つかるかもしれません。

于 2016-05-04T22:54:41.720 に答える