Json 在Play框架中使用Argonaut进行读写
我知道如何使用play应用程序的play json库进行json解析。例如,我有以下代码:Json 在Play框架中使用Argonaut进行读写,json,scala,playframework,argonaut,Json,Scala,Playframework,Argonaut,我知道如何使用play应用程序的play json库进行json解析。例如,我有以下代码: class PersonController extends Controller { case class Person(age: Int, name: String) implicit val personReads = Json.reads[Person] implicit val personWrites = Json.writes[Person] def cre
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 => ...
}
}
}
我应该如何使用Argonaut而不是Play json编写读写之类的代码?Argonaut的代码在这方面相当全面。您需要使用生成一个编解码器
implicit def PersonCodecJson: CodecJson[Person] =
casecodec2(Person.apply, Person.unapply)("age", "name")
然后使用解码验证
返回验证
对象
val result2: Validation[String, Person] =
Parse.decodeValidation[Person](json)
也许这就是你要找的
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
}
}
实际上,您需要一个主体解析器,它使用argonaut而不是play json解析请求主体。希望这能有所帮助。你没有明白我的问题。我想写一些代码来确认Play的可写和可读类型。事实上,我并不是在问验证。你能提供一些背景资料,说明你在做什么,更重要的是,你为什么要这么做吗?