【问题标题】:deserializing models in play 2.2反序列化模型 2.2
【发布时间】: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)
  • 如果 dob address phone 可以为 null,则 Person 案例应将这些字段声明为 Option[String]。建议避免在 scala 中使用null

标签: json scala playframework playframework-2.2


【解决方案1】:

当您使用formatNullable[A] 时,这意味着您将获得Option[A],如果该字段缺失,您将获得None,如果该字段存在,您将获得Some(a: A)

在您的案例类中,您输入了dobaddressphone 作为String,但是在您的格式中您说formatNullable[String],这意味着已解析的值列表与应用您提供的方法 (Person.apply)。错误消息告诉您给定函数的预期参数列表和实际参数列表。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多