问题
I know how to do json parsing using play json library for play application. For example I have following code:
class PersonController extends Controller {
case class Person(age: Int, name: String)
implicit val personReads = Json.reads[Person]
implicit val personWrites = Json.writes[Person]
def create = Action(parse.json) { implicit request =>
rs.body.validate[Person] match {
case s: JsSuccess => ...
case e: JsError => ...
}
}
}
How should I write the code like Reads and Writes using Argonaut instead of Play json?
回答1:
The docs for argonaut are fairly comprehensive in this regard. You need to generate a Codec
with
implicit def PersonCodecJson: CodecJson[Person] =
casecodec2(Person.apply, Person.unapply)("age", "name")
And then use decodeValidation
to get a Validation
object back.
val result2: Validation[String, Person] =
Parse.decodeValidation[Person](json)
回答2:
May be this is what you are looking for?
class PersonController extends Controller {
case class Person(age: Int, name: String)
implicit val PersonCodecJson: CodecJson[Person] =
casecodec2(Person.apply, Person.unapply)("age", "name")
val argonautParser = new BodyParser[Person] {
override def apply(v1: RequestHeader): Iteratee[Array[Byte], Either[Result, Person]] =
}
def argonautParser[T]()(implicit decodeJson: DecodeJson[T]) = parse.text map { body =>
Parse.decodeOption[T](body)
}
def create = Action(argonautParser) { implicit request =>
Ok(request.body.name) //request.body is the decoded value of type Person
}
}
Actually, you need a body parser that parses the request body using argonaut instead of play json. Hope this helps.
来源:https://stackoverflow.com/questions/32833584/use-argonaut-in-play-framework-with-reads-and-writes