[英]Play2.1 Json.validate compiler error “type mismatch; found : *** required: play.api.libs.json.Reads[?]”
[英]Insert logged user id into play.api.libs.json.Reads
我想處理創建新實體的請求,定義如下:
Group (id, name, avatarLink, groupOwnerId)
groupOwnerId是當前登錄用戶的ID。
我以以下方式編寫了讀取對象
implicit val groupReads: Reads[models.GroupDAL.Group] = (
(JsPath \ "name").read[String] and
(JsPath \ "avatarLink").readNullable[String]
)(models.GroupDAL.Group.apply(0L,_,_,0L))
正確設置此變量的正確方法是什么。 從現在開始,我只想到了一個主意-在客戶端的json中設置groupOwnerId值,並創建自定義驗證程序,該驗證程序驗證給定變量是否確實是當前登錄的用戶(因為創建所有者為不同用戶的組是異常的)。
但是IMO,這是一種剛性的解決方案,我必須以這種方式進行,而且我想知道是否在文檔中省略了某件事-也許有更簡單的解決方案。
我想像一下,當您嘗試反序列化JSON值時,您可以在某處獲得登錄用戶的ID。 如果是這樣,該怎么做:
implicit def groupReads(implicit groupOwnerId: Long): Reads[models.GroupDAL.Group] = (
(JsPath \ "name").read[String] and
(JsPath \ "avatarLink").readNullable[String]
)(models.GroupDAL.Group.apply(0L,_,_,groupOwnerId))
這可以讓你寫
val group: Option[Group] = Json.parse(jsonString).asOpt[Group]
只要groupOwnerId
在隱式作用域中可用。 但是,在這種情況下,您可能不想對groupOwnerId
使用Long
,因為這可能導致模棱兩可的隱式值。 一種解決方法是將其包裝在值類中,例如:
class UserId(val underlying: Long) extends AnyVal
並在“ Group
類型的定義中使用該類型:
class Group(id: UserId, name: String, avatarLink: Option[String], groupOwnerId: UserId)
當然,您必須將讀者的簽名更改為:
implicit def groupReads(implicit groupOwnerId: UserId): Reads[models.GroupDAL.Group]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.