Manu Chadha
Manu Chadha

Reputation: 16723

Write JSon deserialiser (Read[T]) for play 2.1.x

Play documentation has following example for creating a Read[T] for a case class. It returns T or throws an exception.

In 2.1.x, it is recommended that JsResult[T] is returned. It should either have T or all the errors. It is also recommended to use JsPath. I am unable to write the reads code for 2.1.x.

This is 2.0.x code from play documentation

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]
    )
  }
}

For 2.1.x, I guess I'll have to do something like

   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.*/
    }
}

Upvotes: 0

Views: 31

Answers (1)

Andriy Kuba
Andriy Kuba

Reputation: 8263

Explanation is in the documentation: 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/

So you reads in 2.1 could be written as

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

Upvotes: 0

Related Questions