2015-10-25 96 views
2

假設我有一個JSON這樣寫的覆蓋值寫入

implicit val userWrites: Writes[User] = (
    (__ \ "name").write[String] ~ 
     (__ \ "email").write[String] ~ 
     (__ \ "encryptedPassword").write[String] ~ 
     (__ \ "id").writeNullable[Long] 
    )(unlift(User.unapply)) 

如果我不想打印輸出的密碼,而不是隻打印一個字符串"hidden",我怎麼可以做到這一點組合子?

我要尋找的是類似於這樣

implicit val userWrites: Writes[User] = (
    (__ \ "name").write[String] ~ 
     (__ \ "email").write[String] ~ 
     (__ \ "encryptedPassword").write[String](Writes.pure("hidden")) ~ 
     (__ \ "id").writeNullable[Long] 
    )(unlift(User.unapply)) 

回答

0

這應該工作:

implicit val userWrites: Writes[User] = (
    (__ \ "name").write[String] ~ 
     (__ \ "email").write[String] ~ 
     (__ \ "encryptedPassword").write[String](Writes((_: String) => JsString("hidden"))) ~ 
     (__ \ "id").writeNullable[Long] 
    )(unlift(User.unapply)) 
+0

感謝@Grisuu。這是我正在尋找的答案。但是,我發現爲不同場景創建不同類的更好的做法,並且只使用默認的JSON讀取和JSON寫入。這比編寫一堆JSON映射代碼要乾淨得多。 – Khanetor

2

你可以做這樣一個解決方案:

implicit val userWrites = new Writes[User] { 
    override def writes(user: User): JsValue = Json.obj(
    "name" -> user.name, 
    "email" -> user.email, 
    "encryptedPassword" -> "hidden", 
    "id" -> user.id 
) 
}