简体   繁体   中英

Play Json: custom reads one field

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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