0

我是 Scala 的新手,我的问题是关于使用 play (2.5) 对 Joda 的可选值 My Inputs: 1 进行 Json 序列化。

import org.joda.time.LocalDateTime
     case class User(
                     name: String, 
                     lastLogin: Option[LocalDateTime])
    object User {
      implicit val serializers = JsonSerializers
      implicit val UserFormat: Format[User] = Format(serializers.UserReads, serializers.UserWrites)
    }
  1. 序列化器

    import com.dtos.{User}
    import org.joda.time.LocalDateTime
    import org.joda.time.format.DateTimeFormat
    import play.api.libs.json._
    import play.api.libs.functional.syntax._
    object JsonSerializers {
      val dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS"
    
      implicit val UserReads: Reads[User] = (
        (JsPath \ "name").read [String] and
          (JsPath \ "active").read [Boolean] and
          (JsPath \\ "$ldt").read[LocalDateTime]
        )(User.apply _)
    
      implicit val UserWrites: Writes[User] = (
        (JsPath \ "name").write [String] and
          (JsPath \ "active").write [Boolean] and
          (JsPath \ "lastLogin" \ "$ldt") .write [LocalDateTime]
        )(unlift (User.unapply))
    }
    
  2. 测试对象:

    object MainTest extends App {    
      val value: JsValue = Json.parse("{ \"name\" : \"hello\" , \"lastLogin\" : {\"$ldt\":\"2018-09-09T11:06:27.655\"} }")
      println("First Output:")
      println(Json.toJson(new MyUser("user", LocalDateTime.now)))
      println("Second Output:")
      println(Json.fromJson(value))    
    }
    

问题: 1. UserReads/UserWrites期间如何管理Option值?我收到以下错误:

重载方法值适用于替代方案: [B](f: B => (String, Boolean, org.joda.time.LocalDateTime))(implicit fu: play.api.libs.functional.ContravariantFunctor[play.api.libs. json.Reads])play.api.libs.json.Reads[B] [B](f: (String, Boolean, org.joda.time.LocalDateTime) => B)(隐式 fu: play.api.libs. functional.Functor[play.api.libs.json.Reads])play.api.libs.json.Reads[B] 不能应用于 ((String, Boolean, Option[org.joda.time.LocalDateTime]) => com.dtos.User) (JsPath\"active").read [Boolean] 和

  1. 当 $ldt 是 lastLogin 的子元素时,无法使其适用于用户的输入 Json 结构:

     val value: JsValue = Json.parse("{ \"name\" : \"hello\" , \"lastLogin\" : {\"$ldt\":\"2018-09-09T11:06:27.655\"} }")
    
    (means User is defined by:
    "name\":\"myName\",
    \"active\":true,
    \"lastLogin\":{\"$ldt\":\"2018-09-09T11:06:27.655\"}
    }
    )
    
4

1 回答 1

0

我认为您缺少的是序列化程序Format[LocalDateTime]

Option支持开箱即用。

取自另一个 Stackoverflow 答案:

import org.joda.time.LocalDateTime
import org.joda.time.format.ISODateTimeFormat

implicit val readsJodaLocalDateTime = Reads[LocalDateTime](js =>
  js.validate[String].map[LocalDateTime](dtString =>
    LocalDateTime.parse(dtString, ISODateTimeFormat.basicDateTime())
  )
)

在这里看到整个答案:custom-jodatime-serializer-using-play-frameworks-json-library

顺便说一句,对于案例类,您可以添加这样的序列化程序:

object User {
  implicit val jsonFormat: Format[User] = Json.format[User]
}
于 2018-09-21T14:02:02.553 回答