[英]Use Argonaut in Play framework with Reads and Writes
I know how to do json parsing using play json library for play application. 我知道如何使用play json库对play应用程序进行json解析。 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? 我应该如何使用Argonaut而不是Play json编写类似读写的代码?
The docs for argonaut are fairly comprehensive in this regard. argonaut的文档在这方面非常全面。 You need to generate a Codec
with 您需要使用生成一个Codec
implicit def PersonCodecJson: CodecJson[Person] =
casecodec2(Person.apply, Person.unapply)("age", "name")
And then use decodeValidation
to get a Validation
object back. 然后使用decodeValidation
取回Validation
对象。
val result2: Validation[String, Person] =
Parse.decodeValidation[Person](json)
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. 实际上,您需要一个主体解析器,该主体解析器使用argonaut而非play json解析请求主体。 Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.