Suj*_*iya 9 json scala slick-3.0 circe
在光滑中使用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))
Run Code Online (Sandbox Code Playgroud)
这是代码,我用于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")
}
Run Code Online (Sandbox Code Playgroud)
BaseEntity:
trait BaseEntity {
val id : Long
def isValid : Boolean = true
}
Run Code Online (Sandbox Code Playgroud)
UserEntity:createdAt生成编码器错误
case class UserEntity(id: Long, email: String, password: String, createdAt: Timestamp) extends BaseEntity
Run Code Online (Sandbox Code Playgroud)
UserEntity:这非常有效
case class UserEntity(id: Long, email: String, password: String) extends BaseEntity
Run Code Online (Sandbox Code Playgroud)
用户表(油滑):
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]
}
Run Code Online (Sandbox Code Playgroud)
我在代码中遗漏了什么吗?任何帮助将受到高度赞赏.
您应该在代码中使用自定义编码器和解码器,类似于:
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)
}
Run Code Online (Sandbox Code Playgroud)
将此val放在需要编码/解码时间戳的任何代码中.例如,您可以将其放在一个对象中,并在需要的地方导入该对象.