Scala + Play Framework + Slick-Json作为模型领域 [英] Scala + Play Framework + Slick - Json as Model Field

查看:97
本文介绍了Scala + Play Framework + Slick-Json作为模型领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将Json字段另存为我的Play框架模型的一列.我在DAO中的表格解析器是

I need to save a Json Field as a column of my Play Framework Model. My table parser in DAO is

    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在播放模型"文件夹中的模型"中定义为案例类,并且具有其伴随对象.该对象的字段为Int,Double或String

Config is defined as a case class in Model in Play Model folder and has his companion object. Field of this object are Int, Double or 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]

    }

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

Problem is i can't compile due to this error

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

Is there a way to save the Config model as Json in the Table (reading it as Config)?

推荐答案

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

You need to tell Slick how to convert your Config instances into database columns:

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

这篇关于Scala + Play Framework + Slick-Json作为模型领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆