我们说我必须为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))
:
Reads
它就像一个魅力,真的(不)。
但是当json对象中只有一个字段时,我该怎么办?
Writes
和import play.api.libs.functional.syntax._
implicit val personReads: Reads[Person] = (
(__ \ "name").read[String]
) (name => Person(name = name))
的核心是功能语法,它可以转换这些"解析"步骤。
以下内容无法编译:
npm install -g node-gyp
你能建议如何处理吗?
答案 0 :(得分:3)
选项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)
}