播放Json:自定义读取一个字段

Play Json: custom reads one field

假设我必须为 Person class:

编写自定义 Reads[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)
}