gpt4 book ai didi

json - 如何使用 Play 框架读取在 JSON 中传递的字符串

转载 作者:行者123 更新时间:2023-12-02 08:26:48 25 4
gpt4 key购买 nike

我在为从客户端传递到服务器的 JSON 编写读取时遇到问题。客户端总是将 id 作为字符串发送,而它们应该是数字。当我尝试将它们读入 Scala 对象时,这会导致问题。我的案例类希望它们是 Long 以与 DB 匹配,但我不确定如何将 String 读取为 Long。我尝试简单地在 employer_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

关于json - 如何使用 Play 框架读取在 JSON 中传递的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31414930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com