假设我必须为Reads[Person]类编写自定义Person:

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))
它的工作原理就像一种魅力,真的(不)。
但是,当json对象中只有一个字段时,我该怎么办?ReadsWrites的核心在于功能语法,该语法可转换这些“解析”步骤。
以下内容无法编译:
import play.api.libs.functional.syntax._

implicit val personReads: Reads[Person] = (
  (__ \ "name").read[String]
)(name => Person(name))
您能建议如何处理吗?

最佳答案

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

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

09-05 17:50