我在 scala 中使用 circe 并有以下要求:
假設我有一些像下面這樣的類,我想避免密碼欄位被序列化,那么有沒有辦法讓 circe 知道它不應該序列化密碼欄位?
在其他庫中,我們有 @transient 之類的注釋,可以防止欄位被序列化,circe 中是否有這樣的注釋?
case class Employee(
name: String,
password: String)
uj5u.com熱心網友回復:
您可以制作一個自定義編碼器來編輯某些欄位:
implicit val encodeEmployee: Encoder[Employee] = new Encoder[Employee] {
final def apply(a: Employee): Json = Json.obj(
("name", Json.fromString(a.name)),
("password", Json.fromString("[REDACTED]")),
)
}
稍后更新
為了避免通過半自動/自動解碼器的所有欄位 contramap:
import io.circe.generic.semiauto._
implicit val encodeEmployee: Encoder[Employee] =
deriveEncoder[Employee]
.contramap[Employee](unredacted => unredacted.copy(password = "[REDACTED]"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/477949.html
