[英]Play Json: custom reads one field
Let's say I have to write custom Reads[Person]
for Person
class:假设我必须为
Person
类编写自定义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))
it works like a charm, really (no).它就像一个魅力,真的(不)。
But what can I do when there is only one field in json object?但是当json对象中只有一个字段时,我该怎么办?
The core of Reads
and Writes
is in functional syntax which transforms these "parse" steps. Reads
and Writes
的核心是转换这些“解析”步骤的函数式语法。
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选项 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选项 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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.