5

假设我必须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 对象中只有一个字段时,我该怎么办?

Reads和的核心在于Writes转换这些“解析”步骤的函数式语法。

以下不编译:

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

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

你能建议如何处理它吗?

4

1 回答 1

9

选项 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)
}
于 2017-11-03T21:04:55.970 回答