使用slick-codegen创建的案例类自动进行JSON编码/解码

时间:2019-05-15 15:55:08

标签: scala playframework slick circe play-json

我使用slick-codegen从数据库生成了我的Scala模型。 现在,Json映射器的生成失败。如何避免手工做任何事情?

绕圈:

could not find implicit value for parameter encoder: io.circe.Encoder[UserController.this.db.UsersRow

play-json:

implicit val userFormat = Json.format[models.Tables#UsersRow]
No unapply or unapplySeq function found for class UsersRow: <none> / <none>

光滑代码生成的代码如下:

package models

object Tables extends {
  val profile = slick.jdbc.PostgresProfile
} with Tables

trait Tables {
  val profile: slick.jdbc.JdbcProfile
  import profile.api._

  case class UsersRow(id: Int, username: String)
  //lots more code
}

1 个答案:

答案 0 :(得分:1)

您可以使用自己的SourceCodeGenerator创建一个圆圈隐式半自动派生 每个案例类别。

https://circe.github.io/circe/codecs/semiauto-derivation.html

代码应类似于...

new slick.codegen.SourceCodeGenerator(model){
  val importCirce =
    "import io.circe.Encoder\nimport io.circe.generic.semiauto._"

  val implicits = model.tables.map(t => {
    val name = entityName(t.name.table)
    s"implicit val ${name}Encoder: Encoder[${name}] = deriveEncoder[${name}]\n"
  }).mkString("\n")

  override def code: String =
    super.code + "\n" + importCirce + "\n\n" + implicits
}

一旦创建模型,您就已经可以使用解码器或编码器

import models.Tables._

val user = new User("Peter", 1)
println {
  user.asJson
}

您可以在此处https://github.com/jgoday/scala-slick-customcodegen

查看完整的示例