5

Let's say I have to write custom Reads[Person] for Person class:

import play.api.libs.functional.syntax._

implicit val personReads: Reads[Person] = (
    (__ \ "name").read[String] and // or ~
    (__ \ "age").readNullable[Int]
) ((name, age) => Person(name = name, age = age))

it works like a charm, really (no).

But what can I do when there is only one field in json object?

The core of Reads and Writes is in functional syntax which transforms these "parse" steps.

The following does not compile:

import play.api.libs.functional.syntax._

implicit val personReads: Reads[Person] = (
  (__ \ "name").read[String]
)(name => Person(name))

Could you advice how to deal with it?

Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96

1 Answers1

10

Option 1: Reads.map

import play.api.libs.json._

case class Person(name: String)

object PlayJson extends App {
  implicit val readsPeson: Reads[Person] =
    (__ \ "name").read[String].map(name => Person(name))

  val rawString = """{"name": "John"}"""
  val json = Json.parse(rawString)
  val person = json.as[Person]
  println(person)
}

Option 2: Json.reads

import play.api.libs.json._

case class Person(name: String)

object Person {
  implicit val readsPerson = Json.reads[Person]
}

object PlayJson extends App { 
  val rawString = """{"name": "John"}"""
  val json = Json.parse(rawString)
  val person = json.as[Person]
  println(person)
}
Mario Galic
  • 47,285
  • 6
  • 56
  • 98