在光滑中使用circe来获取json中的数据时,我可以获取实体中没有日期(Timestamp/DateTime)
字段的数据。但是当我在实体中使用Timestamp
字段时,会抛出错误:
[error] /var/www/html/scala-api/src/main/scala/oc/api/http/routes/TestApi.scala:40: could not find implicit value for parameter encoder: io.circe.Encoder[Seq[oc.api.models.UserEntity]]
[error] auth => complete(userDao.getAll().map(_.asJson))
这是代码,我用于Slick Entities并使用CIRCE进行json编码。
BaseTable:
abstract class BaseTable[T](tag: Tag, name: String) extends Table[T](tag, name) {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def createdAt = column[Timestamp]("created_at")
def updatedAt = column[Timestamp]("updated_at")
def deletedAt = column[Timestamp]("deleted_at")
}
BaseEntity:
trait BaseEntity {
val id : Long
def isValid : Boolean = true
}
UserEntity:createdAt生成编码器错误
case class UserEntity(id: Long, email: String, password: String, createdAt: Timestamp) extends BaseEntity
UserEntity:完美无缺
case class UserEntity(id: Long, email: String, password: String) extends BaseEntity
用户表(油滑):
object UserTables {
class UserTable(tag : Tag) extends BaseTable[UserEntity](tag, "users") {
def name = column[String]("name")
def password = column[String]("password")
def * = (id, name, password) <> (UserEntity.tupled, UserEntity.unapply)
}
implicit val accountsTableQ : TableQuery[UserTable] = TableQuery[UserTable]
}
我在代码中遗漏了什么?任何帮助都将受到高度赞赏。
答案 0 :(得分:8)
您应该在代码中使用自定义编码器和解码器,类似:
implicit val TimestampFormat : Encoder[Timestamp] with Decoder[Timestamp] = new Encoder[Timestamp] with Decoder[Timestamp] {
override def apply(a: Timestamp): Json = Encoder.encodeLong.apply(a.getTime)
override def apply(c: HCursor): Result[Timestamp] = Decoder.decodeLong.map(s => new Timestamp(s)).apply(c)
}
将此val放在需要编码/解码时间戳的任何代码中。例如,您可以将其放在一个对象中,并在需要的地方导入该对象。