I'm trying to define HttpService that receives json and parses it to case class with json4s library:
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()
}
How can I get org.json4s.JsonInput from req.body or req.bodyAsText?
I know that json4s also have StringInput and StreamInput that inherits from JsonInput for using with String and InputStream so I think that I need to convert req.body to InputStream or req.bodyAsText to String but I still do not understand how.
I'm new to Scala and I do not yet fully understand some concepts such as scalaz.stream.Process.
You can use the
http4s-json4s-jackson(orhttp4s-json4s-native) packages and use anorg.http4s.EntityDecoderto easily get aFoo(I renamed yourRequestcase class toFoobelow) from a request.EntityDecoderis a type class which can decode an entity from the request body. We want to get theFooposted in JSON, so we need to create anEntityDecoder[Foo]which can decode JSON. If we want to create this decoder using json4s we need aReader(or aJsonFormat).If you have an
EntityDecoder[Foo]instance, we can get theFoofrom the request withreq.as[Foo].Note: The json libraries libraries used most often with http4s are probably argonaut and circe. So you might find more http4s examples using one of those libraries.