播放文档具有以下示例,用于为案例类创建读取[t]。它返回t或抛出异常。
在2.1.x中,建议返回jsresult [t]。它应该有t或所有错误。还建议使用JSPATH。我无法为2.1.x。
编写读取代码这是play文档中的2.0.x代码
case class Creature(
name: String,
isDead: Boolean,
weight: Float
)
In Play2.0.x, you would write your reader as following:
import play.api.libs.json._
implicit val creatureReads = new Reads[Creature] {
def reads(js: JsValue): Creature = {
Creature(
(js "name").as[String],
(js "isDead").as[Boolean],
(js "weight").as[Float]
)
}
}
对于2.1.x,我想我必须做
之类的事情 implicit val creatureReads = new Reads[Creature] {
def reads(js: JsValue): JsResult[Creature] = {
(JsPath "key1").read[String]
/* at this point, I should either have key1's value or some error. I am clueless how to distinguish between the two and keep processing the rest of the JSon, accumulating all values or errors.*/
}
}
说明在文档中:https://www.playframework.com/documentation/2.2.1/scalajsoncombinatorshttp://mandubian.com/2012/09/08/unveiling-play-2-dot-1-json-api-part1-part1-jspath-reads-combinators/
所以您在2.1中读到可以写为
implicit val creatureReads: Reads[Creature] = (
(__ "name").read[String] and
(__ "isDead").read[Boolean] and
(__ "weight").read[Float]
)(Creature)