gpt4 book ai didi

json - 如何在circe中编码/解码json的时间戳?

转载 作者:行者123 更新时间:2023-12-04 03:56:47 25 4
gpt4 key购买 nike

在 slick 中使用 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 编码。

基表:
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")
}

基础实体:
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]
}

我在代码中遗漏了什么吗?任何帮助将不胜感激。

最佳答案

您应该对您的代码使用自定义编码器和解码器,如下所示:

  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 放在编码/解码时间戳所需的任何代码中。例如,您可以将它放在一个对象中,并在需要的地方导入该对象。

关于json - 如何在circe中编码/解码json的时间戳?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41431085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com