Scala + Play Framework + Slick - Json作为模型领域

时间:2016-11-26 14:34:16

标签: json scala playframework slick play-json

我需要将Json Field保存为Play Framework Model的一列。我在DAO中的表解析器是

    class Table(tag: Tag) extends Table[Model](tag, "tablename") {
      implicit val configFormat = Json.format[Config]

      // Fields ...
      def config = column[Config]("config", O.SqlType("JSON"))
      // Fields ...

    }

Config被定义为模型在Play模型文件夹中的案例类,并具有其伴随对象。该对象的字段是Int,Double或String

    case class Config ( // fields )

    object Config {
      implicit val readConfig: Reads[Config] = new Reads[Config]
      for {
             // fields
      } yield Config(// fields)

      implicit val configFormat = Json.format[Config]

    }

由于此错误,我无法编译问题

    Error:(28, 37) could not find implicit value for parameter tt:         
        slick.ast.TypedType[models.Config]
        def config = column[Config]("config", O.SqlType("JSON"))

有没有办法将Config模型保存为表中的Json(将其读作Config)?

1 个答案:

答案 0 :(得分:4)

您需要告诉Slick如何将Config实例转换为数据库列:

implicit val configFormat = Json.format[Config]
implicit val configColumnType = MappedColumnType.base[Config, String](
  config => Json.stringify(Json.toJson(config)), 
  column => Json.parse(column).as[Config]
)