简体   繁体   English

在Play Framework中使用Reads [T]验证Json

[英]Validating Json with Reads[T] in Play Framework

Looking at a simple Scala Play JSON example (from the Play docs ) to validate JSON (type JsValue ) against a case class : 查看一个简单的Scala Play JSON示例(来自Play 文档 ),以针对case class验证JSON(类型JsValue ):

import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.data.validation.ValidationError

scala> implicit val creatureReads: Reads[Creature] = (
     |  (__ \ "name").read[String] and
     |  (__ \ "isDead").read[Boolean])
<console>:17: error: type mismatch;
 found   : play.api.libs.functional.FunctionalBuilder[play.api.libs.json.Reads]
#CanBuild2[String,Boolean]
 required: play.api.libs.json.Reads[Creature]
        (__ \ "name").read[String] and
                                   ^

Then, eventually call this: 然后,最终称之为:

scala> val creature = Json.obj(  "name" -> "zombie", "isDead" -> true )
creature: play.api.libs.json.JsObject = {"name":"zombie","isDead":true}

scala> creature.validate[Creature]
...

But, how can I resolve the type mismatch I'm seeing? 但是,我怎样才能解决我看到的type mismatch

You're almost there—all you need to do is apply your CanBuild2 to the Creature constructor: 你几乎就在那里 - 你需要做的就是将你的CanBuild2应用于Creature构造函数:

implicit val creatureReads: Reads[Creature] = (
  (__ \ "name").read[String] and (__ \ "isDead").read[Boolean]
)(Creature)

And everything will work as expected. 一切都会按预期工作。 This syntax is a little convoluted, but you can think of it as "lifting" the constructor into the applicative functor for Reads , which allows you to apply it to the two Reads values for the fields. 这种语法有点复杂,但您可以将其视为“将”构造函数“提升”为Reads的applicative functor,它允许您将其应用于字段的两个Reads值。 My answer here refers to Scalaz's applicative builder syntax instead of Play's, but they're essentially the same—just read |@| 我在这里的答案是指Scalaz的应用构建器语法而不是Play的,但它们基本相同 - 只需阅读|@| as and : 作为and

One part of the weirdness is that xs |@| ys 奇怪的一部分是xs |@| ys xs |@| ys doesn't really mean anything on its own—it's essentially an argument list that's waiting to be applied to a function that it will lift into its applicative functor and apply to itself. xs |@| ys本身并不代表任何东西 - 它本质上是一个参数列表,它等待应用于一个函数,它将被提升到它的应用函子并适用于它自己。

See also my answer here and blog post here for additional discussion. 另见我的答案在这里和博客张贴在这里有更多的讨论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM