2017-01-02 68 views
6

雖然使用圓滑在jlick中獲取數據,但我可以在實體中獲取沒有日期(Timestamp/DateTime)字段的數據。但是,當我在實體使用Timestamp領域,則會引發錯誤:如何在circe中對json的時間戳進行編碼/解碼?

[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)) 

下面是代碼,我用油滑的實體和使用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] 
} 

我缺少的代碼的東西嗎?任何幫助將不勝感激。

回答

6

你應該使用自定義編碼器和解碼器的代碼,這樣的事情:

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中的任何代碼需要編碼/解碼時間戳。例如,你可以把它放在一個對象中,並在需要的地方導入對象。

+0

我試圖加入正表作爲 對象UserTables { 類用戶表(標記:標記)延伸BaseTable [UserEntity](標籤, 「用戶」){ DEF的updated_at =柱[選項[字符串]]( 「的updated_at」 ) def * =(...,updated_at)<>(...) } 隱式val TimestampFormat:編碼器[Timestamp]與解碼器[Timestamp] =具有解碼器的新編碼器[Timestamp] [Timestamp] { override def應用(a:時間戳):Json = Encoder.encodeLong.apply(a.getTime) override def apply(c:HCursor):Result [Timestamp] = Decoder.decodeLong.map(s => new Timestamp(s)) .apply(c) } } 但是得到的編碼器錯誤與之前一樣 – Sujit

+0

您必須將val放在實際編碼/解碼的範圍內(所以可能在http相關代碼附近的某處),而不是在sql類中! – C4stor

+0

非常感謝!這就像一個魅力。 :) – Sujit