Json 重头戏2.2中的反序列化模型

Json 重头戏2.2中的反序列化模型,json,scala,playframework,playframework-2.2,Json,Scala,Playframework,Playframework 2.2,在过去的几个小时里,我一直在看的文档,这让我找到了一个模型,它看起来像: case class Person( id: Pk[Long], email: String, isActive: Boolean, firstName: String, lastName: String, gender: String, dob: String, address: String, phone: String) object

在过去的几个小时里,我一直在看的文档,这让我找到了一个模型,它看起来像:

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],字符串,布尔值,字符串,字符串, 字符串,字符串,字符串,字符串,长,长,字符串,字符串)=>models.Person 必需:(anorm.Pk[Long],字符串,布尔值,字符串,字符串,字符串, 选项[String],选项[String],选项[String],长,长,选项[String], 选项[字符串]=>?注意:此处不适用隐式值personReads 因为它位于应用程序点之后,并且缺少显式的结果类型

这很有意义,因为String和Option[String]不一样。我曾尝试将
orElse(null)
getOrElse(null)
添加到可选字段中,但这两个字段都给出了编译时错误,说明这些方法如何在给定对象上不可用


在json中反序列化可选恶魔的正确方法是什么?与带有注释的Jackon相比,当对象上的属性数量增加时,这似乎是不可维护的

当您使用
formatNullable[A]
时,这意味着您将获得一个
选项[A]
None
(如果字段缺失)和
Some(A:A)
(如果字段存在)

在case类中,您键入了
dob
address
phone
作为
String
,但在您的格式中,您说
formatNullable[String]
,这意味着已解析的值列表与您提供的apply方法不匹配(
Person.apply
)。错误消息告诉您给定函数的预期参数列表和实际参数列表


更改case类中的字段、格式或提供一个中间函数而不是
Person。应用
,如果值不存在,则提供默认值,并创建
Person的实例

为什么不使用
Json.Reads
或Json.format`来执行相同的操作?如下所示:
implicit val personFormat=Json.format[Person]
?尝试导致
重载方法值[apply]无法应用于(()=>models.Person)
如果
dob
地址
电话
可以为空,则
Person
案例应将这些字段声明为
选项[String]
。建议避免在scala中使用
null