我是 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)
}
序列化器
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)) }
测试对象:
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] 和
当 $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\"} } )