为JS 2.1编写JSon deserialiser(Read [T])

时间:2017-03-10 22:56:40

标签: json playframework

播放文档有以下示例,用于为案例类创建Read [T]。它返回T或抛出异常。

在2.1.x中,建议返回JsResult [T]。它应该有T或所有错误。还建议使用JsPath。我无法编写2.1.x的读取代码。

这是来自播放文档的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.*/
    }
}

1 个答案:

答案 0 :(得分:0)

说明在文档中: https://www.playframework.com/documentation/2.2.1/ScalaJsonCombinators http://mandubian.com/2012/09/08/unveiling-play-2-dot-1-json-api-part1-jspath-reads-combinators/

所以你读入的2.1可以写成

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