Use Argonaut in Play framework with Reads and Writes

我只是一个虾纸丫 提交于 2020-01-07 09:02:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!