我在编写从客户端传递到服务器的JSON读操作时遇到问题。客户端始终将id作为字符串发送为字符串。当我尝试将它们读入Scala对象时,这会导致问题。我的案例类期望它们为Long以与数据库匹配,但是我不确定如何将String读取为Long。我试过简单地在owner_id上使用.readNullable [Long],但随后它只返回期望jsnumber的验证错误。
Play-Scala 2.4.1
斯卡拉2.11.7
implicit val person_reads: Reads[Person] = (
Reads.pure(-1L) and
Reads.pure(None) and
(JsPath \ "person" \ "given_name").readNullable[String](minLength[String](1)) and
(JsPath \ "person" \ "surname").readNullable[String](minLength[String](1)) and
(JsPath \ "person" \ "city").readNullable[String] and
(JsPath \ "person" \ "state").readNullable[String] and
(JsPath \ "person" \ "county").readNullable[String] and
(JsPath \ "person" \ "zip").readNullable[String] and
(JsPath \ "person" \ "country").readNullable[String] and
(JsPath \ "person" \ "email").readNullable[String](email) and
(JsPath \ "person" \ "phone").readNullable[String] and
(JsPath \ "person" \ "employer_id").readNullable[String] and
Reads.pure(Set[Long]()) and
Reads.pure("") and
Reads.pure("")
)(Person.apply _)
case class Person(
id:Long,
facebook_id:Option[Long],
given_name:Option[String],
surname:Option[String],
city:Option[String],
state:Option[String],
county:Option[String],
zip:Option[String],
country:Option[String],
email:Option[String],
phone:Option[String],
employer_id:Option[Long],
people_connection_ids:Set[Long],
added:String,
modified:String
)
JSON POST / PUT示例
{
"person": {
"id": 78447,
"facebook_id": 12345678987654321,
"given_name": "Jon",
"surname": "Smith",
"city": "",
"state": "",
"county": "",
"zip": "",
"country": "",
"email": "",
"phone": "",
"added": "",
"modified": "",
"employer_id": "1289592", <- This one gets passed as a string instead of number
"people_connection_ids": [
73
]
}
}
谢谢您的帮助
最佳答案
在您的情况下,扩展@cchantep答案,
(JsPath \ "person" \ "employer_id").readNullable[String].map(_.map{_.toLong}) and