【发布时间】:2014-05-08 11:47:53
【问题描述】:
过去几个小时我一直在查看http://www.playframework.com/documentation/2.2.1/ScalaJsonCombinators 的文档,这让我找到了一个看起来像这样的模型:
case class Person(
id: Pk[Long],
email: String,
isActive: Boolean,
firstName: String,
lastName: String,
gender: String,
dob: String,
address: String,
phone: String)
object Person{
implicit object PkFormat extends Format[Pk[Long]] {
def reads(json: JsValue): JsResult[Pk[Long]] = JsSuccess (
json.asOpt[Long].map(id => Id(id)).getOrElse(NotAssigned)
)
def writes(id: Pk[Long]): JsValue = id.map(JsNumber(_)).getOrElse(JsNull)
}
implicit val personFormat = (
(__ \ "id").format[Pk[Long]] ~
(__ \ "email").format[String] ~
(__ \ "isActive").format[Boolean] ~
(__ \ "firstName").format[String] ~
(__ \ "lastName").format[String] ~
(__ \ "gender").format[String] ~
(__ \ "dob").formatNullable[String] ~
(__ \ "address").formatNullable[String] ~
(__ \ "phone").formatNullable[String] ~
)(Person.apply, unlift(Person.unapply))
我收到编译时错误:
类型不匹配;发现 : (anorm.Pk[Long], String, Boolean, String, String, 字符串,字符串,字符串,字符串,长,长,字符串,字符串)=> models.Person 必需:(anorm.Pk[Long],字符串,布尔值,字符串,字符串,字符串, Option[String]、Option[String]、Option[String]、Long、Long、Option[String]、 选项[字符串]) => ?注意:隐式值 personReads 在这里不适用 因为它位于应用程序点之后,并且缺少明确的结果类型
这是有道理的,因为 String 和 Option[String] 不一样。我尝试将orElse(null) 或getOrElse(Null) 添加到可选字段,但两者都给出了关于这些方法在给定对象上不可用的编译时错误。
在 json 中反序列化可选恶魔的正确方法是什么?与带有注释的 Jackon 之类的对象相比,随着对象属性数量的增加,这似乎无法维护。
【问题讨论】:
-
你为什么不使用
Json.Reads或 Json.Format` 来做同样的事情?像这样:implicit val personFormat = Json.format[Person]? -
试过导致
Overloaded method value [apply] cannot be applied to ((<list fields>) => models.Person) -
如果
dobaddressphone可以为 null,则Person案例应将这些字段声明为Option[String]。建议避免在 scala 中使用null。
标签: json scala playframework playframework-2.2